branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>dongyoungy/dbseer_middleware<file_sep>/src/dbseer/middleware/client/MiddlewareClientHandler.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.client;
import com.esotericsoftware.minlog.Log;
import dbseer.middleware.constant.MiddlewareConstants;
import dbseer.middleware.packet.MiddlewarePacket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.io.PrintWriter;
import java.util.Map;
import java.util.zip.ZipOutputStream;
/**
* Created by <NAME> on 12/2/15.
*/
public class MiddlewareClientHandler extends ChannelInboundHandlerAdapter
{
private MiddlewareClient client;
private Map<String,PrintWriter> sysWriter;
private PrintWriter dbWriterRaw;
private ZipOutputStream dbWriter;
public MiddlewareClientHandler(MiddlewareClient client)
{
this.client = client;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
Log.debug("channel read");
MiddlewarePacket packet = (MiddlewarePacket) msg;
int header = packet.header;
if (header == MiddlewareConstants.PACKET_START_MONITORING_SUCCESS)
{
Log.debug("start monitoring succeeded.");
// request server list.
client.requestServerList();
}
else if (header == MiddlewareConstants.PACKET_AUTHENTICATION_FAILURE)
{
Log.debug("authenticaion failed.");
// set monitoring to false
client.setMonitoring(false, packet.body);
}
else if (header == MiddlewareConstants.PACKET_START_MONITORING_FAILURE)
{
Log.debug("start monitoring failed.");
// retry monitoring
client.startMonitoring();
}
else if (header == MiddlewareConstants.PACKET_STOP_MONITORING_SUCCESS)
{
Log.debug("stop monitoring succeeded.");
// set monitoring to false
client.setMonitoring(false);
}
else if (header == MiddlewareConstants.PACKET_STOP_MONITORING_FAILURE)
{
Log.debug("stop monitoring failed.");
// set monitoring to false
client.setMonitoring(false);
}
else if (header == MiddlewareConstants.PACKET_SERVER_LIST)
{
String serverStr = packet.body;
// spawn log requester
dbWriter = client.startTxLogRequester();
dbWriterRaw = client.getTxPrintWriter();
sysWriter = client.startSysLogRequester(serverStr);
// start heartbeat sender
client.startHeartbeatSender();
// set monitoring to true
client.setMonitoring(true, serverStr);
}
else if (header == MiddlewareConstants.PACKET_TX_LOG)
{
Log.debug("received db log.");
// write db log.
dbWriter.write(packet.body.getBytes());
dbWriter.flush();
dbWriterRaw.write(packet.body);
dbWriterRaw.flush();
client.getTxLogRequester().logReceived();
}
else if (header == MiddlewareConstants.PACKET_SYS_LOG)
{
Log.debug("received sys log.");
String[] contents = packet.body.split(MiddlewareConstants.SERVER_STRING_DELIMITER, 2);
String server = contents[0];
String log = contents[1];
// write sys log.
PrintWriter writer = sysWriter.get(server);
writer.write(log);
writer.flush();
client.getSysLogRequester(server).logReceived();
}
else if (header == MiddlewareConstants.PACKET_CONNECTION_DENIED)
{
Log.debug("connection denied");
client.getChannel().close().sync();
// set monitoring to false
client.setMonitoring(false, "Connection denied. It is possible that another DBSeer instance is " +
"connected with the middleware now.");
}
else if (header == MiddlewareConstants.PACKET_CHECK_VERSION_SUCCESS)
{
Log.debug("check version succeeded.");
// start monitoring
client.startMonitoring();
}
else if (header == MiddlewareConstants.PACKET_CHECK_VERSION_FAILURE)
{
Log.debug("check version failed.");
client.getChannel().close().sync();
// set monitoring to false
client.setMonitoring(false);
}
else if (header == MiddlewareConstants.PACKET_TABLE_COUNT)
{
Log.debug("received table count");
String[] contents = packet.body.split(",",3);
String serverName = contents[0];
String tableName = contents[1];
long rowCount = Long.parseLong(contents[2]);
client.setTableRowCount(serverName, tableName, rowCount);
}
else if (header == MiddlewareConstants.PACKET_QUERY_STATISTICS)
{
Log.debug("received query statistics");
String[] contents = packet.body.split(",", 3);
String serverName = contents[0];
int txType = Integer.parseInt(contents[1]);
int reqId = Integer.parseInt(contents[2]);
String rowsAccessed = contents[3];
client.printQueryStatistics(serverName, txType, reqId, rowsAccessed);
}
else if (header == MiddlewareConstants.PACKET_PING)
{
Log.debug("heartbeat received.");
}
else
{
Log.error("Unknown packet received: " + packet.header);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
{
Log.error(this.getClass().getCanonicalName(), "handler caught exception: ", cause);
// set monitoring to false
client.setMonitoring(false, cause.getMessage());
cause.printStackTrace();
ctx.close();
}
}
<file_sep>/rs-sysmon2/examples/devtest.py
#!/usr/bin/python
import sys
sys.path.insert(0, '/usr/share/dstat/')
import dstat, time
devices = (
( 1, 0, 'ram0'),
( 1, 1, 'ram1'),
( 3, 1, 'hda1'),
( 33, 0, 'hde'),
( 7, 0, 'loop0'),
( 7, 1, 'loop1'),
( 8, 0, '/dev/sda'),
( 8, 1, '/dev/sda1'),
( 8, 18, '/dev/sdb2'),
( 8, 37, '/dev/sdc5'),
( 9, 0, 'md0'),
( 9, 1, 'md1'),
( 9, 2, 'md2'),
( 74, 16, '/dev/ida/c2d1'),
( 77, 241, '/dev/ida/c5d15p1'),
( 98, 0, 'ubd/disc0/disc'),
( 98, 16, 'ubd/disc1/disc'),
(104, 0, 'cciss/c0d0'),
(104, 2, 'cciss/c0d0p2'),
(253, 0, 'dm-0'),
(253, 1, 'dm-1'),
)
for maj, min, device in devices:
print device, '->', dstat.dev(maj, min)
<file_sep>/rs-sysmon2/plugins/dstat_battery_remain.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Remaining battery time.
Calculated from power drain and remaining battery power. Information is
retrieved from ACPI.
"""
def __init__(self):
self.name = 'remain'
self.type = 't'
self.width = 5
self.scale = 0
def vars(self):
ret = []
for battery in os.listdir('/proc/acpi/battery/'):
for line in dopen('/proc/acpi/battery/'+battery+'/state').readlines():
l = line.split()
if len(l) < 2: continue
if l[0] == 'present:' and l[1] == 'yes':
ret.append(battery)
ret.sort()
return ret
def nick(self):
return [name.lower() for name in self.vars]
def extract(self):
for battery in self.vars:
for line in dopen('/proc/acpi/battery/'+battery+'/state').readlines():
l = line.split()
if len(l) < 3: continue
if l[0:2] == ['remaining', 'capacity:']:
remaining = int(l[2])
continue
elif l[0:2] == ['present', 'rate:']:
rate = int(l[2])
continue
if rate and remaining:
self.val[battery] = remaining * 60 / rate
else:
self.val[battery] = -1
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_sendmail.py
### Author: <NAME> <<EMAIL>>
### FIXME: Should read /var/log/mail/statistics or /etc/mail/statistics (format ?)
class dstat_plugin(dstat):
def __init__(self):
self.name = 'sendmail'
self.vars = ('queue',)
self.type = 'd'
self.width = 4
self.scale = 100
def check(self):
if not os.access('/var/spool/mqueue', os.R_OK):
raise Exception, 'Cannot access sendmail queue'
def extract(self):
self.val['queue'] = len(glob.glob('/var/spool/mqueue/qf*'))
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_top_mem.py
### Authority: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Most expensive CPU process.
Displays the process that uses the CPU the most during the monitored
interval. The value displayed is the percentage of CPU time for the total
amount of CPU processing power. Based on per process CPU information.
"""
def __init__(self):
self.name = 'most expensive'
self.vars = ('memory process',)
self.type = 's'
self.width = 17
self.scale = 0
def extract(self):
self.val['max'] = 0.0
for pid in proc_pidlist():
try:
### Using dopen() will cause too many open files
l = proc_splitline('/proc/%s/stat' % pid)
except IOError:
continue
if len(l) < 23: continue
usage = int(l[23]) * pagesize
### Is it a new topper ?
if usage <= self.val['max']: continue
self.val['max'] = usage
self.val['name'] = getnamebypid(pid, l[1][1:-1])
self.val['pid'] = pid
self.output = '%-*s%s' % (self.width-5, self.val['name'][0:self.width-5], cprint(self.val['max'], 'f', 5, 1024))
### Debug (show PID)
# self.val['memory process'] = '%*s %-*s' % (5, self.val['pid'], self.width-6, self.val['name'])
def showcsv(self):
return '%s / %d%%' % (self.val['name'], self.val['max'])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_utmp.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'utmp'
self.nick = ('ses', 'usr', 'adm' )
self.vars = ('sessions', 'users', 'root')
self.type = 'd'
self.width = 3
self.scale = 10
def check(self):
try:
global utmp
import utmp
except:
raise Exception, 'Needs python-utmp module'
def extract(self):
for name in self.vars: self.val[name] = 0
for u in utmp.UtmpRecord():
# print '# type:%s pid:%s line:%s id:%s user:%s host:%s session:%s' % (i.ut_type, i.ut_pid, i.ut_line, i.ut_id, i.ut_user, i.ut_host, i.ut_session)
if u.ut_type == utmp.USER_PROCESS:
self.val['users'] = self.val['users'] + 1
if u.ut_user == 'root':
self.val['root'] = self.val['root'] + 1
self.val['sessions'] = self.val['sessions'] + 1
# vim:ts=4:sw=4:et
<file_sep>/src/dbseer/middleware/packet/MiddlewarePacketDecoder.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.packet;
import com.esotericsoftware.minlog.Log;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* Created by <NAME> on 12/2/15.
*/
public class MiddlewarePacketDecoder extends ByteToMessageDecoder
{
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception
{
if (buf.readableBytes() < 8)
{
Log.debug(this.getClass().getCanonicalName(), "buf less than 8 bytes");
return;
}
buf.markReaderIndex();
int header = buf.readInt();
int length = buf.readInt();
if (buf.readableBytes() < length)
{
buf.resetReaderIndex();
Log.debug(this.getClass().getCanonicalName(), "readable bytes less than length = " + length + " and header = " + header);
return;
}
String log = "";
Log.debug(String.format("len = %d, readable = %d", length, buf.readableBytes()));
if (length > 0)
{
byte[] readBuf = new byte[length];
buf.readBytes(readBuf);
log = new String(readBuf, "UTF-8");
}
out.add(new MiddlewarePacket(header, length, log));
}
}
<file_sep>/src/dbseer/middleware/constant/MiddlewareConstants.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.constant;
/**
* Created by <NAME> on 12/1/15.
*/
public class MiddlewareConstants
{
public static final int QUEUE_SIZE = 1800; // equi. 30 min logs
public static final String PROTOCOL_VERSION = "v0.2";
public static final String SERVER_STRING_DELIMITER = ",";
public static final String TX_LOG_RAW = "tx.log";
public static final String TX_LOG_ZIP = "tx.zip";
public static final String SYS_LOG_PREFIX = "sys.log";
public static final int PACKET_PING = 0;
public static final int PACKET_CHECK_VERSION = 10;
public static final int PACKET_CHECK_VERSION_SUCCESS = 11;
public static final int PACKET_CHECK_VERSION_FAILURE = 12;
public static final int PACKET_START_MONITORING = 100;
public static final int PACKET_START_MONITORING_SUCCESS = 101;
public static final int PACKET_START_MONITORING_FAILURE = 102;
public static final int PACKET_STOP_MONITORING = 103;
public static final int PACKET_STOP_MONITORING_SUCCESS = 104;
public static final int PACKET_STOP_MONITORING_FAILURE = 105;
public static final int PACKET_AUTHENTICATION_FAILURE = 106;
public static final int PACKET_REQUEST_TX_LOG = 200;
public static final int PACKET_TX_LOG = 201;
public static final int PACKET_REQUEST_SYS_LOG = 300;
public static final int PACKET_SYS_LOG = 301;
public static final int PACKET_CONNECTION_DENIED = 400;
public static final int PACKET_REQUEST_SERVER_LIST = 500;
public static final int PACKET_SERVER_LIST = 501;
public static final int PACKET_REQUEST_TABLE_COUNT = 600;
public static final int PACKET_TABLE_COUNT = 601;
public static final int PACKET_REQUEST_NUM_ROW_BY_SQL = 700;
public static final int PACKET_NUM_ROW_BY_SQL = 701;
public static final int PACKET_REQUEST_QUERY_STATISTICS = 800;
public static final int PACKET_QUERY_STATISTICS = 801;
}
<file_sep>/rs-sysmon2/plugins/dstat_mysql5_io.py
### Author: <lefred$inuits,be>
global mysql_user
mysql_user = os.getenv('DSTAT_MYSQL_USER') or os.getenv('USER')
global mysql_pwd
mysql_pwd = os.getenv('DSTAT_MYSQL_PWD')
class dstat_plugin(dstat):
"""
Plugin for MySQL 5 I/O.
"""
def __init__(self):
self.name = 'mysql5 io'
self.nick = ('recv', 'sent')
self.vars = ('Bytes_received', 'Bytes_sent')
def check(self):
global MySQLdb
import MySQLdb
try:
self.db = MySQLdb.connect(user=mysql_user, passwd=mysql_pwd)
except:
raise Exception, 'Cannot interface with MySQL server'
def extract(self):
try:
c = self.db.cursor()
c.execute("""show global status like 'Bytes_%';""")
lines = c.fetchall()
for line in lines:
if len(line[1]) < 2: continue
if line[0] in self.vars:
self.set2[line[0]] = float(line[1])
for name in self.vars:
self.val[name] = self.set2[name] * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
except Exception, e:
for name in self.vars:
self.val[name] = -1
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_top_childwait.py
### Dstat most expensive process plugin
### Displays the name of the most expensive process
###
### Authority: <EMAIL>
global cpunr
class dstat_plugin(dstat):
def __init__(self):
self.name = 'most waiting for'
self.vars = ('child process',)
self.type = 's'
self.width = 16
self.scale = 0
def extract(self):
self.set2 = {}
self.val['max'] = 0.0
for pid in proc_pidlist():
try:
### Using dopen() will cause too many open files
l = proc_splitline('/proc/%s/stat' % pid)
except IOError:
continue
if len(l) < 15: continue
### Reset previous value if it doesn't exist
if not self.set1.has_key(pid):
self.set1[pid] = 0
self.set2[pid] = int(l[15]) + int(l[16])
usage = (self.set2[pid] - self.set1[pid]) * 1.0 / elapsed / cpunr
### Is it a new topper ?
if usage <= self.val['max']: continue
self.val['max'] = usage
self.val['name'] = getnamebypid(pid, l[1][1:-1])
self.val['pid'] = pid
### Debug (show PID)
# self.val['process'] = '%*s %-*s' % (5, self.val['pid'], self.width-6, self.val['name'])
if step == op.delay:
self.set1 = self.set2
def show(self):
if self.val['max'] == 0.0:
return '%-*s' % (self.width, '')
else:
return '%s%-*s%s' % (theme['default'], self.width-3, self.val['name'][0:self.width-3], cprint(self.val['max'], 'p', 3, 34))
def showcsv(self):
return '%s / %d%%' % (self.val['name'], self.val['max'])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_mysql5_conn.py
### Author: <lefred$inuits,be>
global mysql_user
mysql_user = os.getenv('DSTAT_MYSQL_USER') or os.getenv('USER')
global mysql_pwd
mysql_pwd = os.getenv('DSTAT_MYSQL_PWD')
class dstat_plugin(dstat):
"""
Plugin for MySQL 5 connections.
"""
def __init__(self):
self.name = 'mysql5 conn'
self.nick = ('ThCon', '%Con')
self.vars = ('Threads_connected', 'Threads')
self.type = 'f'
self.width = 4
self.scale = 1
def check(self):
global MySQLdb
import MySQLdb
try:
self.db = MySQLdb.connect(user=mysql_user, passwd=mysql_pwd)
except Exception, e:
raise Exception, 'Cannot interface with MySQL server, %s' % e
def extract(self):
try:
c = self.db.cursor()
c.execute("""show global variables like 'max_connections';""")
max = c.fetchone()
c.execute("""show global status like 'Threads_connected';""")
thread = c.fetchone()
if thread[0] in self.vars:
self.set2[thread[0]] = float(thread[1])
self.set2['Threads'] = float(thread[1]) / float(max[1]) * 100.0
for name in self.vars:
self.val[name] = self.set2[name] * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
except Exception, e:
for name in self.vars:
self.val[name] = -1
# vim:ts=4:sw=4:et
<file_sep>/build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="dbseer_middleware" default="all">
<!--<property file="build.properties"/>-->
<!-- Uncomment the following property if no tests compilation is needed -->
<!--
<property name="skip.tests" value="true"/>
-->
<!-- Compiler options -->
<property name="compiler.debug" value="on"/>
<property name="compiler.generate.no.warnings" value="off"/>
<property name="compiler.args" value=""/>
<property name="compiler.max.memory" value="700m"/>
<patternset id="ignored.files">
<exclude name="**/*.hprof/**"/>
<exclude name="**/*.pyc/**"/>
<exclude name="**/*.pyo/**"/>
<exclude name="**/*.rbc/**"/>
<exclude name="**/*~/**"/>
<exclude name="**/.DS_Store/**"/>
<exclude name="**/.git/**"/>
<exclude name="**/.hg/**"/>
<exclude name="**/.svn/**"/>
<exclude name="**/CVS/**"/>
<exclude name="**/RCS/**"/>
<exclude name="**/SCCS/**"/>
<exclude name="**/__pycache__/**"/>
<exclude name="**/_svn/**"/>
<exclude name="**/rcs/**"/>
<exclude name="**/vssver.scc/**"/>
<exclude name="**/vssver2.scc/**"/>
</patternset>
<patternset id="library.patterns">
<include name="*.war"/>
<include name="*.swc"/>
<include name="*.apk"/>
<include name="*.zip"/>
<include name="*.ear"/>
<include name="*.egg"/>
<include name="*.ane"/>
<include name="*.jar"/>
</patternset>
<patternset id="compiler.resources">
<exclude name="**/?*.java"/>
<exclude name="**/?*.form"/>
<exclude name="**/?*.class"/>
<exclude name="**/?*.groovy"/>
<exclude name="**/?*.scala"/>
<exclude name="**/?*.flex"/>
<exclude name="**/?*.kt"/>
<exclude name="**/?*.clj"/>
<exclude name="**/?*.aj"/>
</patternset>
<!-- Project Libraries -->
<path id="library.commons-cli-1.3.1.classpath">
<pathelement location="${basedir}/lib/commons-cli-1.3.1.jar"/>
</path>
<path id="library.commons-io-2.4.classpath">
<pathelement location="${basedir}/lib/commons-io-2.4.jar"/>
</path>
<path id="library.commons-lang3-3.4.classpath">
<pathelement location="${basedir}/lib/commons-lang3-3.4.jar"/>
</path>
<path id="library.ini4j-0.5.4.classpath">
<pathelement location="${basedir}/lib/ini4j-0.5.4.jar"/>
</path>
<path id="library.minlog-1.2.classpath">
<pathelement location="${basedir}/lib/minlog-1.2.jar"/>
</path>
<path id="library.mysql-connector-java-5.1.37-bin.classpath">
<pathelement location="${basedir}/lib/mysql-connector-java-5.1.37-bin.jar"/>
</path>
<path id="library.netty-all-4.0.33.final.classpath">
<pathelement location="${basedir}/lib/netty-all-4.0.33.Final.jar"/>
</path>
<path id="library.jzlib-1.1.3.classpath">
<pathelement location="${basedir}/lib/jzlib-1.1.3.jar"/>
</path>
<!-- Modules -->
<!-- Module dbseer_middleware -->
<dirname property="module.dbseer_middleware.basedir" file="${ant.file}"/>
<property name="compiler.args.dbseer_middleware" value="-encoding UTF-8 -source 7 -target 7 ${compiler.args}"/>
<property name="dbseer_middleware.output.dir" value="${module.dbseer_middleware.basedir}/out/production/dbseer_middleware"/>
<property name="dbseer_middleware.testoutput.dir" value="${module.dbseer_middleware.basedir}/out/test/dbseer_middleware"/>
<path id="dbseer_middleware.module.bootclasspath">
<!-- Paths to be included in compilation bootclasspath -->
</path>
<path id="dbseer_middleware.module.production.classpath">
<path refid="library.netty-all-4.0.33.final.classpath"/>
<path refid="library.commons-cli-1.3.1.classpath"/>
<path refid="library.commons-io-2.4.classpath"/>
<path refid="library.ini4j-0.5.4.classpath"/>
<path refid="library.minlog-1.2.classpath"/>
<path refid="library.commons-lang3-3.4.classpath"/>
<path refid="library.mysql-connector-java-5.1.37-bin.classpath"/>
<path refid="library.jzlib-1.1.3.classpath"/>
</path>
<path id="dbseer_middleware.runtime.production.module.classpath">
<pathelement location="${dbseer_middleware.output.dir}"/>
<path refid="library.netty-all-4.0.33.final.classpath"/>
<path refid="library.commons-cli-1.3.1.classpath"/>
<path refid="library.commons-io-2.4.classpath"/>
<path refid="library.ini4j-0.5.4.classpath"/>
<path refid="library.minlog-1.2.classpath"/>
<path refid="library.commons-lang3-3.4.classpath"/>
<path refid="library.mysql-connector-java-5.1.37-bin.classpath"/>
<path refid="library.jzlib-1.1.3.classpath"/>
</path>
<path id="dbseer_middleware.module.classpath">
<pathelement location="${dbseer_middleware.output.dir}"/>
<path refid="library.netty-all-4.0.33.final.classpath"/>
<path refid="library.commons-cli-1.3.1.classpath"/>
<path refid="library.commons-io-2.4.classpath"/>
<path refid="library.ini4j-0.5.4.classpath"/>
<path refid="library.minlog-1.2.classpath"/>
<path refid="library.commons-lang3-3.4.classpath"/>
<path refid="library.mysql-connector-java-5.1.37-bin.classpath"/>
<path refid="library.jzlib-1.1.3.classpath"/>
</path>
<path id="dbseer_middleware.runtime.module.classpath">
<pathelement location="${dbseer_middleware.testoutput.dir}"/>
<pathelement location="${dbseer_middleware.output.dir}"/>
<path refid="library.netty-all-4.0.33.final.classpath"/>
<path refid="library.commons-cli-1.3.1.classpath"/>
<path refid="library.commons-io-2.4.classpath"/>
<path refid="library.ini4j-0.5.4.classpath"/>
<path refid="library.minlog-1.2.classpath"/>
<path refid="library.commons-lang3-3.4.classpath"/>
<path refid="library.mysql-connector-java-5.1.37-bin.classpath"/>
<path refid="library.jzlib-1.1.3.classpath"/>
</path>
<patternset id="excluded.from.module.dbseer_middleware">
<patternset refid="ignored.files"/>
</patternset>
<patternset id="excluded.from.compilation.dbseer_middleware">
<patternset refid="excluded.from.module.dbseer_middleware"/>
</patternset>
<path id="dbseer_middleware.module.sourcepath">
<dirset dir="${module.dbseer_middleware.basedir}">
<include name="src"/>
</dirset>
</path>
<target name="compile.module.dbseer_middleware" depends="compile.module.dbseer_middleware.production,compile.module.dbseer_middleware.tests" description="Compile module dbseer_middleware"/>
<target name="compile.module.dbseer_middleware.production" description="Compile module dbseer_middleware; production classes">
<mkdir dir="${dbseer_middleware.output.dir}"/>
<javac destdir="${dbseer_middleware.output.dir}" debug="${compiler.debug}" nowarn="${compiler.generate.no.warnings}" memorymaximumsize="${compiler.max.memory}" fork="true">
<compilerarg line="${compiler.args.dbseer_middleware}"/>
<bootclasspath refid="dbseer_middleware.module.bootclasspath"/>
<classpath refid="dbseer_middleware.module.production.classpath"/>
<src refid="dbseer_middleware.module.sourcepath"/>
<patternset refid="excluded.from.compilation.dbseer_middleware"/>
</javac>
<copy todir="${dbseer_middleware.output.dir}">
<fileset dir="${module.dbseer_middleware.basedir}/src">
<patternset refid="compiler.resources"/>
<type type="file"/>
</fileset>
</copy>
</target>
<target name="compile.module.dbseer_middleware.tests" depends="compile.module.dbseer_middleware.production" description="compile module dbseer_middleware; test classes" unless="skip.tests"/>
<target name="clean.module.dbseer_middleware" description="cleanup module">
<delete dir="${dbseer_middleware.output.dir}"/>
<delete dir="${dbseer_middleware.testoutput.dir}"/>
</target>
<target name="init" description="Build initialization">
<!-- Perform any build initialization in this target -->
<property name="src" value="src" />
<property name="bin" value="bin" />
<property name="lib" value="lib" />
<property name="middleware_version" value="0.2" />
</target>
<target name="clean" depends="init">
<delete dir="${bin}" />
</target>
<target name="prepare" depends="clean">
<mkdir dir="${bin}" />
</target>
<target name="compile" depends="prepare">
<javac srcdir="${src}" destdir="${bin}" >
<compilerarg line="${compiler.args.dbseer_middleware}"/>
<bootclasspath refid="dbseer_middleware.module.bootclasspath"/>
<classpath refid="dbseer_middleware.module.production.classpath"/>
</javac>
</target>
<target name="jar" depends="compile">
<jar destfile="dbseer-middleware-${middleware_version}.jar" basedir="${bin}">
<zipgroupfileset dir="${lib}" includes="*.jar"/>
</jar>
</target>
<target name="clean.module" depends="clean.module.dbseer_middleware" description="cleanup all"/>
<target name="build.modules" depends="init, clean.module, compile.module.dbseer_middleware" description="build all modules"/>
<target name="all" depends="compile ,build.modules" description="build all"/>
</project>
<file_sep>/rs-sysmon2/plugins/dstat_vmk_hba.py
### Author: <NAME> <bert+dstat$debruijn,be>
### VMware ESX kernel vmhba stats
### Displays kernel vmhba statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -D argument.
# EXAMPLES:
# # dstat --vmkhba -D vmhba1,vmhba2,total
# # dstat --vmkhba -D vmhba0
# You can even combine the Linux and VMkernel diskstats (but the "total" argument
# will be used by both).
# # dstat --vmkhba -d -D sda,vmhba1
class dstat_plugin(dstat):
def __init__(self):
self.name = 'vmkhba'
self.nick = ('read', 'writ')
self.cols = 2
def discover(self, *list):
# discover will list all vmhba's found.
# we might want to filter out the unused vmhba's (read stats, compare with ['0', ] * 13)
ret = []
try:
list = os.listdir('/proc/vmware/scsi/')
except:
raise Exception, 'Needs VMware ESX'
for name in list:
for line in dopen('/proc/vmware/scsi/%s/stats' % name).readlines():
l = line.split()
if len(l) < 13: continue
if l[0] == 'cmds': continue
if l == ['0', ] * 13: continue
ret.append(name)
return ret
def vars(self):
# vars will take the argument list - when implemented - , use total, or will use discover + total
ret = []
if op.disklist:
list = op.disklist
#elif not op.full:
# list = ('total', )
else:
list = self.discover
list.sort()
for name in list:
if name in self.discover + ['total']:
ret.append(name)
return ret
def check(self):
try:
os.listdir('/proc/vmware')
except:
raise Exception, 'Needs VMware ESX'
info(1, 'The vmkhba module is an EXPERIMENTAL module.')
def extract(self):
self.set2['total'] = (0, 0)
for name in self.vars:
self.set2[name] = (0, 0)
for name in os.listdir('/proc/vmware/scsi/'):
for line in dopen('/proc/vmware/scsi/%s/stats' % name).readlines():
l = line.split()
if len(l) < 13: continue
if l[0] == 'cmds': continue
if l[2] == '0' and l[4] == '0': continue
if l == ['0', ] * 13: continue
self.set2['total'] = ( self.set2['total'][0] + long(l[2]), self.set2['total'][1] + long(l[4]) )
if name in self.vars and name != 'total':
self.set2[name] = ( long(l[2]), long(l[4]) )
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 1024.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 1024.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
<file_sep>/rs-sysmon2/plugins/dstat_rpc.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'rpc client'
self.nick = ('call', 'retr', 'refr')
self.vars = ('calls', 'retransmits', 'autorefreshes')
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/net/rpc/nfs')
def extract(self):
for l in self.splitlines():
if not l or l[0] != 'rpc': continue
for i, name in enumerate(self.vars):
self.set2[name] = long(l[i+1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/examples/mstat.py
#!/usr/bin/python
### Example2: simple sub-second monitor (ministat)
### This is a quick example showing how to implement your own *stat utility
### If you're interested in such functionality, contact me at <EMAIL>
import sys
sys.path.insert(0, '/usr/share/dstat/')
import dstat, time
### Set default theme
dstat.theme = dstat.set_theme()
### Allow arguments
try: delay = float(sys.argv[1])
except: delay = 0.2
try: count = int(sys.argv[2])
except: count = 10
### Load stats
stats = []
dstat.starttime = time.time()
dstat.tick = dstat.ticks()
for o in (dstat.dstat_epoch(), dstat.dstat_cpu(), dstat.dstat_mem(), dstat.dstat_load(), dstat.dstat_disk(), dstat.dstat_sys()):
try: o.check()
except Exception, e: print e
else: stats.append(o)
### Make time stats sub-second
stats[0].format = ('t', 14, 0)
### Print headers
title = subtitle = ''
for o in stats:
title = title + ' ' + o.title()
subtitle = subtitle + ' ' + o.subtitle()
print '\n' + title + '\n' + subtitle
### Print stats
for dstat.update in range(count):
line = ''
for o in stats:
o.extract()
line = line + ' ' + o.show()
print line + dstat.ansi['reset']
if dstat.update != count-1: time.sleep(delay)
dstat.tick = 1
print dstat.ansi['reset']
<file_sep>/rs-sysmon2/plugins/dstat_vmk_nic.py
### Author: <NAME> <bert+dstat$debruijn,be>
### VMware ESX kernel vmknic stats
### Displays VMkernel port statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -N argument.
# EXAMPLES:
# # dstat --vmknic -N vmk1
# You can even combine the Linux and VMkernel network stats (just don't just "total").
# # dstat --vmknic -n -N vmk0,vswif0
# NB Data comes from /proc/vmware/net/tcpip/ifconfig
class dstat_plugin(dstat):
def __init__(self):
self.name = 'vmknic'
self.nick = ('recv', 'send')
self.open('/proc/vmware/net/tcpip/ifconfig')
self.cols = 2
def check(self):
try:
os.listdir('/proc/vmware')
except:
raise Exception, 'Needs VMware ESX'
info(1, 'The vmknic module is an EXPERIMENTAL module.')
def discover(self, *list):
ret = []
for l in self.fd[0].splitlines(replace=' /', delim='/'):
if len(l) != 12: continue
if l[2][:5] == '<Link': continue
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] == 'lo0': continue
if l[0] == 'Usage:': continue
ret.append(l[0])
ret.sort()
for item in list: ret.append(item)
return ret
def vars(self):
ret = []
if op.netlist:
list = op.netlist
else:
list = self.discover
list.sort()
for name in list:
if name in self.discover + ['total']:
ret.append(name)
return ret
def name(self):
return ['net/'+name for name in self.vars]
def extract(self):
self.set2['total'] = [0, 0]
for line in self.fd[0].readlines():
l = line.replace(' /','/').split()
if len(l) != 12: continue
if l[2][:5] == '<Link': continue
if ','.join(l) == 'Name,Mtu/TSO,Network,Address,Ipkts,Ierrs,Ibytes,Opkts,Oerrs,Obytes,Coll,Time': continue
if l[0] == 'Usage:': continue
name = l[0]
if name in self.vars:
self.set2[name] = ( long(l[6]), long(l[9]) )
if name != 'lo0':
self.set2['total'] = ( self.set2['total'][0] + long(l[6]), self.set2['total'][1] + long(l[9]) )
if update:
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 1.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 1.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4
<file_sep>/rs-sysmon2/plugins/dstat_vz_io.py
### Author: <NAME> <<EMAIL>>
### Example content for /proc/bc/<veid>/ioacct
# read 2773011640320
# write 2095707136000
# dirty 4500342390784
# cancel 4080624041984
# missed 0
# syncs_total 2
# fsyncs_total 1730732
# fdatasyncs_total 3266
# range_syncs_total 0
# syncs_active 0
# fsyncs_active 0
# fdatasyncs_active 0
# range_syncs_active 0
# vfs_reads 3717331387
# vfs_read_chars 3559144863185798078
# vfs_writes 901216138
# vfs_write_chars 23864660931174682
# io_pbs 16
class dstat_plugin(dstat):
def __init__(self):
self.nick = ['read', 'write', 'dirty', 'cancel', 'missed']
self.cols = len(self.nick)
def check(self):
if not os.path.exists('/proc/vz'):
raise Exception, 'System does not have OpenVZ support'
elif not os.path.exists('/proc/bc'):
raise Exception, 'System does not have (new) OpenVZ beancounter support'
elif not glob.glob('/proc/bc/*/ioacct'):
raise Exception, 'System does not have any OpenVZ containers'
info(1, 'Module %s is still experimental.' % self.filename)
def name(self):
return ['ve/'+name for name in self.vars]
def vars(self):
ret = []
if not op.full:
varlist = ['total',]
else:
varlist = [os.path.basename(veid) for veid in glob.glob('/proc/vz/*')]
ret = varlist
return ret
def extract(self):
for veid in self.vars:
self.set2['total'] = {}
for line in dopen('/proc/bc/%s/ioacct' % veid).readlines():
l = line.split()
if len(l) != 2: continue
if l[0] not in self.nick: continue
index = self.nick.index(l[0])
self.set2[veid][index] = long(l[1])
self.set2['total'][index] = self.set2['total'][index] + long(l[1])
# print veid, self.val[veid], self.set2[veid][0], self.set2[veid][1]
# print veid, self.val[veid], self.set1[veid][0], self.set1[veid][1]
for i in range(len(self.nick)):
self.val[veid][i] = (self.set2[veid][i] - self.set1[veid][i]) / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_ntp.py
### Author: <NAME> <<EMAIL>>
global socket
import socket
global struct
import struct
### FIXME: Implement millisecond granularity as well
### FIXME: Interrupts socket if data is overdue (more than 250ms ?)
class dstat_plugin(dstat):
"""
Time from an NTP server.
BEWARE: this dstat plugin typically takes a lot longer to run than
system plugins and for that reason it is important to use an NTP server
located nearby as well as make sure that it does not impact your other
counters too much.
"""
def __init__(self):
self.name = 'ntp'
self.nick = ('date/time',)
self.vars = ('time',)
self.timefmt = os.getenv('DSTAT_TIMEFMT') or '%d-%m %H:%M:%S'
self.ntpserver = os.getenv('DSTAT_NTPSERVER') or '0.fedora.pool.ntp.org'
self.type = 's'
self.width = len(time.strftime(self.timefmt, time.localtime()))
self.scale = 0
self.epoch = 2208988800L
# socket.setdefaulttimeout(0.25)
self.socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
self.socket.settimeout(0.25)
def gettime(self):
self.socket.sendto( '\x1b' + 47 * '\0', ( self.ntpserver, 123 ))
data, address = self.socket.recvfrom(1024)
return struct.unpack( '!12I', data )[10] - self.epoch
def check(self):
try:
self.gettime()
except socket.gaierror:
raise Exception, 'Failed to connect to NTP server %s.' % self.ntpserver
except socket.error:
raise Exception, 'Error connecting to NTP server %s.' % self.ntpserver
def extract(self):
try:
self.val['time'] = time.strftime(self.timefmt, time.localtime(self.gettime()))
except:
self.val['time'] = theme['error'] + '-'.rjust(self.width-1) + ' '
def showcsv(self):
return time.strftime(self.timefmt, time.localtime(self.gettime()))
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_top_oom.py
### Author: <NAME> <<EMAIL>>
### Dstat most expensive process plugin
### Displays the name of the most expensive process
### More information:
### http://lwn.net/Articles/317814/
class dstat_plugin(dstat):
def __init__(self):
self.name = 'out of memory'
self.vars = ('kill score',)
self.type = 's'
self.width = 18
self.scale = 0
def check(self):
if not os.access('/proc/self/oom_score', os.R_OK):
raise Exception, 'Kernel does not support /proc/pid/oom_score, use at least 2.6.11.'
def extract(self):
self.output = ''
self.val['max'] = 0.0
for pid in proc_pidlist():
try:
### Extract name
name = proc_splitline('/proc/%s/stat' % pid)[1][1:-1]
### Using dopen() will cause too many open files
l = proc_splitline('/proc/%s/oom_score' % pid)
except IOError:
continue
except IndexError:
continue
if len(l) < 1: continue
oom_score = int(l[0])
### Is it a new topper ?
if oom_score <= self.val['max']: continue
self.val['max'] = oom_score
self.val['name'] = getnamebypid(pid, name)
self.val['pid'] = pid
if self.val['max'] != 0.0:
self.output = '%-*s%s' % (self.width-4, self.val['name'][0:self.width-4], cprint(self.val['max'], 'f', 4, 1000))
### Debug (show PID)
# self.output = '%*s %-*s' % (5, self.val['pid'], self.width-6, self.val['name'])
def showcsv(self):
return '%s / %d%%' % (self.val['name'], self.val['max'])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_client_latency.py
### Author: <EMAIL>
class dstat_plugin(dstat):
"""
EVENTS COMMENT.
"""
def __init__(self):
self.name = 'latency'
self.type = 'p'
self.width = 4
self.scale = 34
def vars(self):
ret = []
for name in glob.glob('/tmp/dstat/sla/client[0-9]*'):
ret.append(os.path.basename(name))
ret.sort()
return ret
def nick(self):
return [name.lower() for name in self.vars]
def extract(self):
for csla in self.vars:
f = open('/tmp/dstat/sla/'+csla+'/latency', 'r')
st = f.readline().rstrip()
if(st == ""):
self.val[csla] = 0
else:
self.val[csla] = float(st)
f.close()
def check(self):
for csla in glob.glob('/tmp/dstat/sla/client[0-9]*'):
if not os.access(csla+'/latency', os.R_OK):
raise Exception, 'Cannot access latency %s information' % os.path.basename(csla)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/examples/dstat.py
dstat-0.7.2/../dstat<file_sep>/rs-sysmon2/plugins/dstat_helloworld.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Example "Hello world!" output plugin for aspiring Dstat developers.
"""
def __init__(self):
self.name = 'plugin title'
self.nick = ('counter',)
self.vars = ('text',)
self.type = 's'
self.width = 12
self.scale = 0
def extract(self):
self.val['text'] = 'Hello world!'
# vim:ts=4:sw=4:et
<file_sep>/src/dbseer/middleware/packet/MiddlewarePacketEncoder.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
* Created by <NAME> on 5/6/16.
*/
public class MiddlewarePacketEncoder extends MessageToByteEncoder<MiddlewarePacket>
{
@Override
protected void encode(ChannelHandlerContext ctx, MiddlewarePacket packet, ByteBuf buf) throws Exception
{
buf.writeInt(packet.header);
buf.writeInt(packet.length);
if (packet.length > 0)
{
buf.writeBytes(packet.body.getBytes("UTF-8"));
}
}
}
<file_sep>/rs-sysmon2/plugins/dstat_thermal.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'thermal'
self.type = 'd'
self.width = 3
self.scale = 20
if os.path.exists('/proc/acpi/ibm/thermal'):
self.namelist = ['cpu', 'pci', 'hdd', 'cpu', 'ba0', 'unk', 'ba1', 'unk']
self.nick = []
for line in dopen('/proc/acpi/ibm/thermal'):
l = line.split()
for i, name in enumerate(self.namelist):
if int(l[i+1]) > 0:
self.nick.append(name)
self.vars = self.nick
elif os.path.exists('/proc/acpi/thermal_zone/'):
self.vars = os.listdir('/proc/acpi/thermal_zone/')
# self.nick = [name.lower() for name in self.vars]
self.nick = []
for name in self.vars:
self.nick.append(name.lower())
else:
raise Exception, 'Needs kernel ACPI or IBM-ACPI support'
def check(self):
if not os.path.exists('/proc/acpi/ibm/thermal') and not os.path.exists('/proc/acpi/thermal_zone/'):
raise Exception, 'Needs kernel ACPI or IBM-ACPI support'
def extract(self):
if os.path.exists('/proc/acpi/ibm/thermal'):
for line in dopen('/proc/acpi/ibm/thermal'):
l = line.split()
for i, name in enumerate(self.namelist):
if int(l[i+1]) > 0:
self.val[name] = int(l[i+1])
elif os.path.exists('/proc/acpi/thermal_zone/'):
for zone in self.vars:
for line in dopen('/proc/acpi/thermal_zone/'+zone+'/temperature').readlines():
l = line.split()
self.val[zone] = int(l[1])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_nfsd3.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'nfs3 server'
self.nick = ('read', 'writ', 'rdir', 'inod', 'fs', 'cmmt')
self.vars = ('read', 'write', 'readdir', 'inode', 'filesystem', 'commit')
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/net/rpc/nfsd')
def check(self):
info(1, 'Module %s is still experimental.' % self.filename)
def extract(self):
for l in self.splitlines():
if not l or l[0] != 'proc3': continue
self.set2['read'] = long(l[8])
self.set2['write'] = long(l[9])
self.set2['readdir'] = long(l[18]) + long(l[19])
self.set2['inode'] = long(l[3]) + long(l[4]) + long(l[5]) + long(l[6]) + long(l[7]) + long(l[10]) + long(l[11]) + long(l[12]) + long(l[13]) + long(l[14]) + long(l[15]) + long(l[16]) + long(l[17])
self.set2['filesystem'] = long(l[20]) + long(l[21]) + long(l[22])
self.set2['commit'] = long(l[23])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_dstat_cpu.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Provide CPU information related to the dstat process.
This plugin shows the CPU utilization for the dstat process itself,
including the user-space and system-space (kernel) utilization and
a total of both. On a system with one cpu and one core, the total
cputime is 1000ms. On a system with 2 cores the total is 2000ms.
It may help to vizualise the performance of Dstat and its selection
of plugins.
"""
def __init__(self):
self.name = 'dstat cpu'
self.vars = ('user', 'system', 'total')
self.type = 'd'
self.width = 4
self.scale = 100
def extract(self):
res = resource.getrusage(resource.RUSAGE_SELF)
self.set2['user'] = float(res.ru_utime)
self.set2['system'] = float(res.ru_stime)
self.set2['total'] = float(res.ru_utime) + float(res.ru_stime)
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1000.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_battery.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Percentage of remaining battery power as reported by ACPI.
"""
def __init__(self):
self.name = 'battery'
self.type = 'p'
self.width = 4
self.scale = 34
def check(self):
if not os.path.exists('/proc/acpi/battery/'):
raise Exception, "No ACPI battery information found."
def vars(self):
ret = []
for battery in os.listdir('/proc/acpi/battery/'):
for line in dopen('/proc/acpi/battery/'+battery+'/state').readlines():
l = line.split()
if len(l) < 2: continue
if l[0] == 'present:' and l[1] == 'yes':
ret.append(battery)
ret.sort()
return ret
def nick(self):
return [name.lower() for name in self.vars]
def extract(self):
for battery in self.vars:
for line in dopen('/proc/acpi/battery/'+battery+'/info').readlines():
l = line.split()
if len(l) < 4: continue
if l[0] == 'last':
full = int(l[3])
break
for line in dopen('/proc/acpi/battery/'+battery+'/state').readlines():
l = line.split()
if len(l) < 3: continue
if l[0] == 'remaining':
current = int(l[2])
break
if current:
self.val[battery] = current * 100.0 / full
else:
self.val[battery] = -1
# vim:ts=4:sw=4:et
<file_sep>/middleware_client.sh
#!/bin/bash
BIN_PATH=bin:lib/*
java -cp "$BIN_PATH" dbseer.middleware.test.MiddlewareClientTest $@
<file_sep>/rs-sysmon2/plugins/dstat_wifi.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'wifi'
self.nick = ('lnk', 's/n')
self.type = 'd'
self.width = 3
self.scale = 34
self.cols = 2
def check(self):
global iwlibs
from pythonwifi import iwlibs
def vars(self):
return iwlibs.getNICnames()
def extract(self):
for name in self.vars:
wifi = iwlibs.Wireless(name)
stat, qual, discard, missed_beacon = wifi.getStatistics()
# print qual.quality, qual.signallevel, qual.noiselevel
if qual.quality == 0 or qual.signallevel == -101 or qual.noiselevel == -101 or qual.signallevel == -256 or qual.noiselevel == -256:
self.val[name] = ( -1, -1 )
else:
self.val[name] = ( qual.quality, qual.signallevel * 100 / qual.noiselevel )
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_vm_memctl.py
### Author: <NAME> <bert+dstat$debruijn,be>
### VMware vmmemctl stats
### Displays ballooning status inside VMware VMs.
### The vmmemctl from the VMware Tools needs to be loaded.
### This plugin has been tested on a VM running CentOS5 with the open-vm-tools, on ESX3.5
# NB Data comes from /proc/vmmemctl
class dstat_plugin(dstat):
def __init__(self):
self.name = 'memctl'
self.nick = ('size',)
self.vars = ('balloon',)
self.type = 'f'
self.width = 6
self.scale = 1024
self.open('/proc/vmmemctl')
def check(self):
try:
os.stat('/proc/vmmemctl')
except:
raise Exception, 'Needs VMware Tools (modprobe vmmemctl)'
def extract(self):
for l in self.splitlines():
if len(l) < 3: continue
if l[0] != 'current:': continue
if l[2] != 'pages': continue
self.val['balloon'] = int(l[1]) * 4096.0
break
# vim:ts=4:sw=4
<file_sep>/README.md
# DBSeer Middleware
DBSeer middleware collects various statistics from OS and DBMS and transfers them to DBSeer for its performance prediction and analysis.
The middleware requires MariaDB MaxScale with the dbseerroute plugin, which is a custom router plugin that is necessary to collect required transaction information.
The MariaDB MaxScale with the dbseerroute plugin is available [here](https://github.com/dongyoungy/MaxScale).
**NOTE: DBSeer middleware and the dbseerroute plugin require `autocommit` option from MySQL/MariaDB to be OFF as it detects 'rollback' or 'commit' statements to distinguish different transactions.**
## Installation
DBSeer middleware requires the following:
* Java 1.7+
* Apache Ant
* Python 2.7+ and MySQL-python (for *rs-sysmon*)
DBSeer middleware can be compiled with `ant` command:
$ ant
Once the compilation is successful, you can launch the middleware by running `middleware.sh` at the root directory of the package.
$ ./middleware.sh
When the middleware starts successfully, you will see the following messages in the terminal:
```
$ ./middleware.sh
00:00 INFO: Listening port = 3555
00:00 INFO: DB log dir = /tmp/maxscale/perf.log
00:00 INFO: System log dir = /tmp/maxscale
00:00 INFO: [Server : server1]
00:00 INFO: DB Host = localhost
00:00 INFO: DB Port = 3400
00:00 INFO: DB User = root
00:00 INFO: DB PW =
00:00 INFO: SSH User = dyoon
00:00 INFO: Remote Monitor Dir = /home/user/middleware/rs-sysmon2
00:00 INFO: Remote Monitor Script = monitor.sh
00:00 INFO: Middleware is now accepting connections.
```
The diagram below demonstrates a basic setup of DBSeer middleware and MaxScale for collecting OS/DBMS and query statistics from a single MySQL/MariaDB server (i.e., ***System Z*** in the diagram. There can be multiple ***'System Z'***s depending on the MaxScale configuration).
![DBSeer Layout](http://i.imgur.com/KeHG8Ll.png)
DBSeer middleware and MariaDB MaxScale must run on the same machine (i.e., ***System Y***). The middleware needs to be deployed at the MySQL/MariaDB server side in order to collect OS/DBMS statistics (i.e., ***System Z***).
The middleware includes a variant of system monitoring utility called *rs-sysmon* under the directory *rs-sysmon2*. *rs-sysmon* requires Python 2.7+ and MySQL-python installed, so in this example setup, they need to be installed in ***System Z***. The middleware runs the utility remotely via ssh to collect OS/DBMS statistics.
Using the above diagram as an example, a user must have a system account that can access ***System Z*** via *ssh* without authorization from ***System Y***. This can be done by adding the public key of the account at ***System Y*** as an authorized key for the account at ***System Z***. Using `ssh-copy-id` is the easiest way to set this up.
## Configuration
DBSeer middleware reads its configuration from `middleware.cnf`.
The following is a sample of the configuration file:
```
[dbseer_middleware]
# middleware user id
id=dbseer
# # middleware user password
password=<PASSWORD>
# port that middleware listens to for the communication with DBSeer
listen_port=3555
# path of the named pipe that dbseerroute uses to communicate with the middleware.
named_pipe=/tmp/dbseerroute
# middleware reads the SQL performance log from this file.
dblog_path=/tmp/maxscale/perf.log
# middleware writes OS/DBMS statistics of each server into separate files in this directory.
syslog_dir=/tmp/maxscale
# the list of MySQL/MariaDB servers
servers=server1
# server1 configuration start
[server1]
# SQL credential necessary for middleware to gather the DBMS statistics (it uses "SHOW GLOBAL STATUS")
db_host=localhost
db_port=3400
db_user=root
db_pw=
# you must be able to run monitor script remotely at server1 using the following configuration.
ssh_user=dyoon
monitor_dir=/home/user/middleware/rs-sysmon2
monitor_script=monitor.sh
# server1 configuration end
```
### id
`id` specifies an id that DBSeer needs to use for authentication.
### password
`password` specifies a password that DBSeer needs to use for authentication.
### listen_port
`listen_port` specifies the port that the middleware listens for the communication with DBSeer.
### named_pipe
`named_pipe` is tha path of the named pipe that **dbseerroute** plugin from our custom version of MariaDB MaxScale uses to communicate with the middleware.
### dblog_path
`dblog_path` should be the filename of the log file generated by the **dbseerroute** plugin from MariaDB MaxScale. DBSeer middleware continuously reads the transaction information (e.g., SQL statement, latency, etc.) from the file and transfers them to DBSeer while it is monitoring.
### syslog_dir
`syslog_dir` specifies the directory where the middleware collects and writes OS/DBMS log data that are not transaction-related. You specify a directory rather than a file here, because there can be more than one MySQL/MariaDB servers running under MariaDB. DBSeer middleware will generate a log file for each server under the directory. Each file will have the format of `sys.log.<server name>`.
### servers
`servers` provides a list of MySQL/MariaDB servers, which MaxScale will connect to. Each server is separated by a comma:
servers=server1,server2,server3
**NOTE: each server on the list must have its own section in the configuration file where it is defined.**
### db_host
`db_host` specifies the IP address or hostname of a MySQL/MariaDB server.
### db_port
`db_port` specifies the port of a MySQL/MariaDB server.
### db_user
`db_user` specifies the username of a MySQL/MariaDB server, which the middleware will use to collect MySQL statistics (*by running 'SHOW GLOBAL STATUS'*).
### db_pw
`db_pw` specifies the password for the user `db_user`.
### ssh_user
`ssh_user` specifies the username of *nix account that is used to run *rs-sysmon2* remotely.
### monitor_dir
`monitor_dir` specifies the directory where *rs-sysmon2* is located.
### monitor_script
`monitor_script` specifies the filename of the script that executes *rs-sysmon2* (*default: monitor.sh*).
<file_sep>/rs-sysmon2/plugins/dstat_top_int.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Top interrupt
Displays the name of the most frequent interrupt
"""
def __init__(self):
self.name = 'most frequent'
self.vars = ('interrupt',)
self.type = 's'
self.width = 20
self.scale = 0
self.intset1 = [ 0 ] * 256
self.open('/proc/stat')
self.names = self.names()
def names(self):
ret = {}
for line in dopen('/proc/interrupts'):
l = line.split()
if len(l) <= cpunr: continue
l1 = l[0].split(':')[0]
### Cleanup possible names from /proc/interrupts
l2 = ' '.join(l[cpunr+2:])
l2 = l2.replace('_hcd:', '/')
l2 = re.sub('@pci[:\d+\.]+', '', l2)
ret[l1] = l2
return ret
def extract(self):
self.output = ''
self.val['total'] = 0.0
for line in self.splitlines():
if line[0] == 'intr':
self.intset2 = [ long(int) for int in line[3:] ]
for i in range(len(self.intset2)):
total = (self.intset2[i] - self.intset1[i]) * 1.0 / elapsed
### Put the highest value in self.val
if total > self.val['total']:
if str(i+1) in self.names.keys():
self.val['name'] = self.names[str(i+1)]
else:
self.val['name'] = 'int ' + str(i+1)
self.val['total'] = total
if step == op.delay:
self.intset1 = self.intset2
if self.val['total'] != 0.0:
self.output = '%-15s%s' % (self.val['name'], cprint(self.val['total'], 'd', 5, 1000))
def showcsv(self):
return '%s / %f' % (self.val['name'], self.val['total'])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_dstat.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Provide more information related to the dstat process.
The dstat cputime is the total cputime dstat requires per second. On a
system with one cpu and one core, the total cputime is 1000ms. On a system
with 2 cores the total is 2000ms. It may help to vizualise the performance
of Dstat and its selection of plugins.
"""
def __init__(self):
self.name = 'dstat'
self.vars = ('cputime', 'latency')
self.type = 'd'
self.width = 4
self.scale = 100
self.open('/proc/%s/schedstat' % ownpid)
def extract(self):
l = self.splitline()
# l = linecache.getline('/proc/%s/schedstat' % self.pid, 1).split()
self.set2['cputime'] = long(l[0])
self.set2['latency'] = long(l[1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/examples/read.py
#!/usr/bin/python
### Example 1: Direct accessing stats
### This is a quick example showing how you can access dstat data
### If you're interested in this functionality, contact me at <EMAIL>
import sys
sys.path.insert(0, '/usr/share/dstat/')
import dstat
### Set default theme
dstat.theme = dstat.set_theme()
clear = dstat.ansi['reset']
dstat.tick = dstat.ticks()
c = dstat.dstat_cpu()
print c.title() + '\n' + c.subtitle()
c.extract()
print c.show(), clear
print 'Percentage:', c.val['total']
print 'Raw:', c.cn2['total']
print
m = dstat.dstat_mem()
print m.title() + '\n' + m.subtitle()
m.extract()
print m.show(), clear
print 'Raw:', m.val
print
l = dstat.dstat_load()
print l.title() + '\n' + l.subtitle()
l.extract()
print l.show(), clear
print 'Raw:', l.val
print
d = dstat.dstat_disk()
print d.title() + '\n' + d.subtitle()
d.extract()
print d.show(), clear
print 'Raw:', d.val['total']
print
<file_sep>/rs-sysmon2/plugins/dstat_cpufreq.py
### Author: <EMAIL>
class dstat_plugin(dstat):
"""
CPU frequency in percentage as reported by ACPI.
"""
def __init__(self):
self.name = 'frequency'
self.type = 'p'
self.width = 4
self.scale = 34
def check(self):
for cpu in glob.glob('/sys/devices/system/cpu/cpu[0-9]*'):
if not os.access(cpu+'/cpufreq/scaling_cur_freq', os.R_OK):
raise Exception, 'Cannot access acpi %s frequency information' % os.path.basename(cpu)
def vars(self):
ret = []
for name in glob.glob('/sys/devices/system/cpu/cpu[0-9]*'):
ret.append(os.path.basename(name))
ret.sort()
return ret
# return os.listdir('/sys/devices/system/cpu/')
def nick(self):
return [name.lower() for name in self.vars]
def extract(self):
for cpu in self.vars:
for line in dopen('/sys/devices/system/cpu/'+cpu+'/cpufreq/scaling_max_freq').readlines():
l = line.split()
max = int(l[0])
for line in dopen('/sys/devices/system/cpu/'+cpu+'/cpufreq/scaling_cur_freq').readlines():
l = line.split()
cur = int(l[0])
### Need to close because of bug in sysfs (?)
dclose('/sys/devices/system/cpu/'+cpu+'/cpufreq/scaling_cur_freq')
self.set1[cpu] = self.set1[cpu] + cur * 100.0 / max
if op.update:
self.val[cpu] = self.set1[cpu] / elapsed
else:
self.val[cpu] = self.set1[cpu]
if step == op.delay:
self.set1[cpu] = 0
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_lustre.py
# Author: <NAME> <<EMAIL>>, <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.nick = ('read', 'write')
def check(self):
if not os.path.exists('/proc/fs/lustre/llite'):
raise Exception, 'Lustre filesystem not found'
info(1, 'Module %s is still experimental.' % self.filename)
def name(self):
return [mount for mount in os.listdir('/proc/fs/lustre/llite')]
def vars(self):
return [mount for mount in os.listdir('/proc/fs/lustre/llite')]
def extract(self):
for name in self.vars:
for l in open(os.path.join('/proc/fs/lustre/llite', name, 'stats')).splitlines():
if len(l) < 6: continue
if l[0] == 'read_bytes':
read = long(l[6])
elif l[0] == 'write_bytes':
write = long(l[6])
self.set2[name] = (read, write)
self.val[name] = ( (self.set2[name][0] - self.set1[name][0]) * 1.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 1.0 / elapsed )
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4
<file_sep>/rs-sysmon2/plugins/dstat_top_latency_avg.py
### Dstat most expensive I/O process plugin
### Displays the name of the most expensive I/O process
###
### Authority: <EMAIL>
### For more information, see:
### http://eaglet.rain.com/rick/linux/schedstat/
class dstat_plugin(dstat):
def __init__(self):
self.name = 'highest average'
self.vars = ('latency process',)
self.type = 's'
self.width = 17
self.scale = 0
self.pidset1 = {}
def check(self):
if not os.access('/proc/self/schedstat', os.R_OK):
raise Exception, 'Kernel has no scheduler statistics, use at least 2.6.12'
def extract(self):
self.output = ''
self.pidset2 = {}
self.val['result'] = 0
for pid in proc_pidlist():
try:
### Reset values
if not self.pidset1.has_key(pid):
self.pidset1[pid] = {'wait_ticks': 0, 'ran': 0}
### Extract name
name = proc_splitline('/proc/%s/stat' % pid)[1][1:-1]
### Extract counters
l = proc_splitline('/proc/%s/schedstat' % pid)
except IOError:
continue
except IndexError:
continue
if len(l) != 3: continue
self.pidset2[pid] = {'wait_ticks': long(l[1]), 'ran': long(l[2])}
if self.pidset2[pid]['ran'] - self.pidset1[pid]['ran'] > 0:
avgwait = (self.pidset2[pid]['wait_ticks'] - self.pidset1[pid]['wait_ticks']) * 1.0 / (self.pidset2[pid]['ran'] - self.pidset1[pid]['ran']) / elapsed
else:
avgwait = 0
### Get the process that spends the most jiffies
if avgwait > self.val['result']:
self.val['result'] = avgwait
self.val['pid'] = pid
self.val['name'] = getnamebypid(pid, name)
if step == op.delay:
self.pidset1 = self.pidset2
if self.val['result'] != 0.0:
self.output = '%-*s%s' % (self.width-4, self.val['name'][0:self.width-4], cprint(self.val['result'], 'f', 4, 100))
### Debug (show PID)
# self.output = '%*s %-*s' % (5, self.val['pid'], self.width-6, self.val['name'])
def showcsv(self):
return '%s / %.4f' % (self.val['name'], self.val['result'])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_proc_count.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Total Number of processes on this system.
"""
def __init__(self):
self.name = 'procs'
self.vars = ('total',)
self.type = 'd'
self.width = 4
self.scale = 10
def extract(self):
self.val['total'] = len([pid for pid in proc_pidlist()])
<file_sep>/rs-sysmon2/examples/mmpipe.py
#!/usr/bin/python
import select, sys, os
def readpipe(file, tmout = 0.001):
"Read available data from pipe"
ret = ''
while not select.select([file.fileno()], [], [], tmout)[0]:
pass
while select.select([file.fileno()], [], [], tmout)[0]:
ret = ret + file.read(1)
return ret.split('\n')
def dpopen(cmd):
"Open a pipe for reuse, if already opened, return pipes"
global pipes
if 'pipes' not in globals().keys(): pipes = {}
if cmd not in pipes.keys():
pipes[cmd] = os.popen3(cmd, 't', 0)
return pipes[cmd]
### Unbuffered sys.stdout
sys.stdout = os.fdopen(1, 'w', 0)
### Main entrance
if __name__ == '__main__':
try:
stdin, stdout, stderr = dpopen('/usr/lpp/mmfs/bin/mmpmon -p -s')
stdin.write('reset\n')
readpipe(stdout)
while True:
stdin.write('io_s\n')
for line in readpipe(stdout):
print line
except KeyboardInterrupt, e:
print
# vim:ts=4:sw=4
<file_sep>/rs-sysmon2/examples/tdbtest
#!/usr/bin/python
import sys, tdb
db = tdb.tdb('/var/cache/samba/connections.tdb')
print db.keys()
key=db.firstkey()
while key:
print db.fetch(key)
key=db.nextkey(key)
db = tdb.tdb('/var/cache/samba/locking.tdb')
print db.keys
db = tdb.tdb('/var/cache/samba/sessionid.tdb')
print db.keys
<file_sep>/rs-sysmon2/plugins/dstat_snooze.py
class dstat_plugin(dstat):
def __init__(self):
self.name = 'snooze'
self.vars = ('snooze',)
self.type = 's'
self.width = 6
self.scale = 0
self.before = time.time()
def extract(self):
now = time.time()
if loop != 0:
self.val['snooze'] = now - self.before
else:
self.val['snooze'] = self.before
if step == op.delay:
self.before = now
def show(self):
if self.val['snooze'] > step + 1:
return ansi['default'] + ' -'
color = 'white'
if step != op.delay:
color = 'gray'
snoze, c = fchg(self.val['snooze'], 6, 1000)
return ansi[color] + snoze
<file_sep>/rs-sysmon2/plugins/dstat_mysql_ndb.py
### Author: <lefred$inuits,be> modified by: <<EMAIL>>
global mysql_user
mysql_user = os.getenv('DSTAT_MYSQL_USER') or os.getenv('USER')
global mysql_pwd
mysql_pwd = os.getenv('DSTAT_MYSQL_PWD')
global mysql_host
mysql_host = os.getenv('DSTAT_MYSQL_HOST')
global mysql_port
mysql_port = os.getenv('DSTAT_MYSQL_PORT')
print "in mysql plugin"
class dstat_plugin(dstat):
"""
Plugin for MySQL NDB.
"""
def __init__(self):
self.name = 'mysql-ndb on ' + mysql_host +' ' + mysql_port
self.nick = ("Data memory", "Index memory", "REDO", "ndbnodecount", "DATA_MEMORY", "DISK_OPERATIONS", "DISK_RECORDS", "FILE_BUFFERS", "JOBBUFFER", "RESERVED", "TRANSPORT_BUFFERS")
self.vars = ("Data memory", "Index memory", "REDO", "ndbnodecount", "DATA_MEMORY", "DISK_OPERATIONS", "DISK_RECORDS", "FILE_BUFFERS", "JOBBUFFER", "RESERVED", "TRANSPORT_BUFFERS")
def check(self):
global MySQLdb
import MySQLdb
try:
print mysql_host, mysql_port, mysql_user, mysql_pwd
self.db = MySQLdb.connect(host=mysql_host,port=int(mysql_port), user=mysql_user, passwd=mysql_pwd)
except:
raise Exception, 'Cannot interface with MySQL server'
def extract(self):
try:
c = self.db.cursor()
c.execute("select memory_type, avg(used) from ndbinfo.memoryusage group by memory_type;")
lines = c.fetchall()
for line in lines:
if len(line) < 2: continue
if line[0] in self.vars:
self.set2[line[0]] = int(line[1])
c.execute("""select log_type, avg(used) from ndbinfo.logbuffers group by log_type;""")
lines = c.fetchall()
for line in lines:
if len(line) < 2: continue
if line[0] in self.vars:
self.set2[line[0]] = int(line[1])
c.execute("""select 'ndbnodecount' as var, count(*) from ndbinfo.nodes where status = 'STARTED';""")
lines = c.fetchall()
for line in lines:
if len(line) < 2: continue
if line[0] in self.vars:
self.set2[line[0]] = int(line[1])
c.execute("""select resource_name, avg(used) from ndbinfo.resources group by resource_name;""")
lines = c.fetchall()
for line in lines:
if len(line) < 2: continue
if line[0] in self.vars:
self.set2[line[0]] = int(line[1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
except Exception, e:
for name in self.vars:
self.val[name] = -1
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/dstat-docs/dstat-paper.txt
= Dstat: plugin-based real-time monitoring
<NAME> <<EMAIL>>
$Id$
== Introduction
Many tools exist to monitor hardware resources and software behaviour, but few
tools exist that allow you to easily monitor any conceivable counter.
Dstat was designed with the idea that it should be simple to plug in a piece
of code that extracts one or more counters, and make it visible in a way that
visually pleases the eye and helps you extract information in real-time.
By being able to select those counters that you want (and likely those
counters that matter to you in the job you're doing) you make it easier to
correlate raw numbers and see a pattern that may otherwise not be visible.
== A case for Dstat
A few years ago I was involved in a project that was testing a storage cluster
with a SAN back-end using GPFS and Samba for a broadcasting company. The
performance tests that were scheduled together with the customer took a few
weeks to measure the different behaviour under different stresses.
During these tests there was a need to see how each of the components behaved
and to find problematic behaviour during testing. Also, because it involved 5
GPFS nodes, we needed to make sure that the load was spread evenly during the
test. If everything went well repeatedly, the results were validated and the
next batch of tests could be prepared and run.
We started off using different tools at first, but the more counters we were
trying to capture the harder it was to post-process the information we had
collected. What's more, we often saw only after performing the tests that the
data was not representative because the numbers didn't add up. Sometimes it
was caused by the massive setup of clients that were autonomously stressing the
cluster. On other occasions we noticed that the network was the culprit. All in
all, we lost time because we could only validate the results by relating
numbers after the tests were complete and not during the tests.
Complicating the matter was the fact that 5 different nodes were involved
and using the normal command line tools like vmstat, iostat or ifstat (which
only showed us a small part of what was happening) was problematic as each
needed a different terminal. Besides, not all information was interesting.
Eventually Dstat was born, to make a dull task more enjoyable.
After the project was finished I was able to correlate system resources with
network throughput, TCP information, Samba sessions, GPFS throughput,
accumulated block device throughput, HBA throughput, all within a single
interval.
== Dstat characteristics
There are many ideas incorporated into Dstat by design, and this section
serves to list all of them. Not all of them may appeal to the task you're
doing, but the combination may make it an appealing proposition nevertheless.
=== History of counters
An important characteristic in tools like vmstat, iostat or ifstat is the fact
that you can compare historical collected data with new data. This allows you
to have a good feeling of how something is evolving.
Compare this to tools like top or nmon, where data is often being refreshed
and you loose historical information.
=== Adding unit indication
It was very important that when numbers were compared, they were in the same
unit, and not eg. a different power exponent. The human mind sometimes works
in mysterious ways and more so when working with numbers for hours and hours.
Adding the unit is something very convenient and may reduce the human error
factor.
Additionally, indicating the unit also makes sure that the columns have a
fixed width. Often when using vmstat or other tools, the columns tend to shift
depending on the width of the counter. This makes it very inconvenient to find
counters in the shifted output.
=== Colour highlighting units
After I added colours to help improve indicating units, I noticed that the
colours also helped to show patterns. This of course is very limited,
nevertheless it instantly shows when numbers are flat or changes are taking
place.
IMPORTANT: The colours are arbitrarily chosen. Do not make the mistake to
assume that green means good and red means bad. There is no real meaning to
the colour itself, however a change of colour does mean that a value has gone
over some pre-defined limit.
=== Intermediate updates
During tests, when you choose to see average values over a given time, it can
be useful to see how the averages evolve. Dstat, by default, displays
intermediate updates. This means that if you select to see 10 second averages,
after each second you see the accumulated average over the timespan. *This
means that after 4 seconds with intermediate updates, you see an average
taken over the 4 second timeframe.*
NOTE: This means that the closer you get to the given timeframe (eg. 10 seconds)
the more likely that it nears its final average over that period.
=== Adding custom counters
Dstat was specifically designed to enable anyone to add their own counters in a
matter of minutes. The plugin-based system takes care of displaying, colouring
and adding units to the counters. As a plugin-writer, you only have to focus
on extracting the counters from the kernel (procfs or sysfs), logfiles or
daemons.
=== Selecting plugins and counters
Being able to add custom counters is important, but selecting those counters
that you really need is even more important if you want to correlate counters
and see patterns. Less is more.
NOTE: In fact, Dstat currently does not allow you to select just counters, it
only allows you to select plugins. However, since you can modify or fork a
plugin, you still have the ability to select just those counters you prefer.
=== Exporting to CSV
Having information on screen is one thing, you most likely need some hard
evidence later to make your case. (Why else do all the work?)
Dstat allows to write out all counters in the greatest detail possible to CSV.
By default it also adds the command-line used for generating the output, as
well as a date and time stamp. Since Dstat in the first place is meant for
human-readable real-time statistics, it will by default also display the
counters to screen (unless you _/dev/null_ it).
TIP: Dstat appends to the output file so that you can add tests-results of
different tests to a single file. However, make sure that you tag each test
properly (eg. by using distinct filenames for each different test).
=== Time-plugin included
It may seem a small thing, but having exact time (and date) information for
your counters allows for a completely different usage as well. By adding
simple date and time information, Dstat can be used as a background process in
a screen to monitor the behaviour of your system during the night.
This proves to be very valuable for example, to find offending processes during
nightly tasks or to pinpoint their behaviour to certain events that you cannot
monitor during working hours.
It is also important when you have multiple Dstats running (eg. for nodes in a
cluster) to correlate counters between the outputs.
=== Terminal capabilities
Dstat also takes into account the width and height of your terminal window and
modifies output to fit into your terminal. This, of course, has no effect on
what ends up in the CSV output.
Another (debatable) useful feature is that Dstat will modify the terminal
title to indicate on what system it was run and what options were used.
Especially when monitoring nodes in a cluster, this can be useful, but even in
Gnome finding your Dstat window is handy.
WARNING: Some people however are annoyed by the fact that their distribution
does not reset the terminal title and Dstat therefor messes it up. There is no
way for Dstat to fix this.
== Plugins and counters
When we talk about plugins, we make a distinction between those plugins that
are included within the Dstat tool itself, and those that ship with it
externally. In essence there is no real difference, as the internal plugins
could easily have been created as an external plugin. The basic difference is
that the internal plugins have no dependencies except on procfs.
Having the basic plugins as part of Dstat, makes sure that Dstat can be moved
as a self-contained file to other systems.
=== Internal plugins
The plugins that have been selected to be part of the Dstat tool itself, and
therefor have no dependencies other than procfs, are:
- aio: asynchronous I/O counters
- cpu, cpu24: CPU counters (+-c+ and +-C+)
- disk, disk24, disk24old: disk counters (+-d+ and +-D+)
- epoch: seconds since Epoch (+-T+)
- fs: file system counters
- int, int24: interrupts per IRQ (+-i+ and +-I+)
- io: I/O requests completed (+-r+)
- ipc: IPC counters
- load: load counters (+-l+)
- lock: locking counters
- mem: memory usage (+-m+)
- net: network usage (+-n+ and +-N+)
- page, page24: paging counters (+-g+)
- proc: process counters (+-p+)
- raw: raw socket counters
- swap, swapold: swap usage (+-s+ and +-S+)
- socket: socket counters
- sys: system (kernel) countersA (+-y+)
- tcp: TCP socket counters
- time: date and time (+-t+)
- udp: UDP socket counters
- unix: unix socket counters
- vm: virtual memory counters
For backward compatibility with older kernels there is a cascading system that
selects the most appropriate internal plugin for your kernel. (eg. the
+dstat_disk+ plugin falls back to +dstat_disk24+ and +dstat_disk24old+) At this
moment there is no such system for external plugins.
=== External plugins
This basic functionality is easily extended by writing your own plugins
(subclasses of the python Dstat class) which are then inserted at runtime
into Dstat. A set of 'external' modules exist for:
- battery: battery usage
- battery-remain: remaining battery time
- cpufreq: CPU frequency
- dbus: DBUS connections
- disk-util: disk utilization percentage
- fan: Fan speed
- freespace: free space on filesystems
- gpfs: GPFS IO counters
- gpfs-ops: GPFS operations counters
- helloworld: Hello world dispenser
- innodb-buffer: innodb buffer counters
- innodb-io: innodb I/O counters
- innodb-keys: innodb key operation counters
- innodb-ops: innodb operations counters
- lustre: lustre throughput counters
- memcache-hits: Memcache hit counters
- mysql5-cmds: MySQL communication counters
- mysql5-conn: MySQL connection counters
- mysql5-io: MySQL I/O counters
- mysql5-keys: MySQL keys counters
- mysql-io: MySQL I/O counters
- mysql-ops: MySQL operations counters
- nfs3-ops: NFS3 client operations counters
- nfs3: NFS3 client counters
- nfsd3-ops: NFS3 server operations counters
- nfsd3: NFS3 server counters
- ntp: NTP time counters
- postfix: postfix queue counters
- power: Power usage counters
- rpcd: RPC server counters
- rpc: RPC client counters
- sendmail: sendmail queue counters
- snooze: Dstat time delay counters
- thermal: Thermal counters
- top-bio: most expensive block I/O process
- top-cpu: most expensive cpu process
- top-cputime: process using the most CPU time
- top-cputime-avg: process having the highest average CPU time
- top-io: most expensive I/O process
- top-latency: process with the highest total latency
- top-latency-avg: process with the highest average latency
- top-mem: most expensive memory process
- top-oom: process first shot by OOM killer
- utmp: utmp counters
- vmk-hba: VMware kernel HBA counters
- vmk-int: VMware kernel interrupt counters
- vmk-nic: VMware kernel NIC counters
- vm-memctl: VMware guest memory counters
- vz-cpu: OpenVZ CPU counters
- vz-ubc: OpenVZ user beancounters
- wifi: WIFI quality information
=== Most-wanted plugins
Hoping someone interested reads this document, I added a few plugins that
would be ``very nice'' to have but are currently lacking:
- slab: needs a VM expert to make sense out of the vast amount of data
- xorg: need information on how to get X resources, would be nice
to see evolution of X resources over time
- samba: lacking information to get counters from Samba without
forking smbstatus every second
- snmp: could be useful to relate counters from different systems
in a single Dstat
- topx: display the most expensive X application(s)
- systemtap: connecting Dstat to systemtap counters
Creative souls with other ideas are welcome as well !
== Using Dstat
Central to the Dstat command line interface is the selection of plugins. The
selection and order of options influence the Dstat output directly.
=== Enabling plugins
The internal plugins have short and/or long options within Dstat, eg. +-c+ or
+--cpu+ will enable the cpu counters.
The external plugins are enable by a long option including their name,
eg. +--top-cpu+
The following examples will enable the time, cpu and disk plugins, and are
equal.
----
dstat -tcd
dstat --time --cpu --disk
----
=== Total or individual counters
Some of the plugins can show both total values or individual values and
therefor have an extra option to influence this decision.
----
dstat -d -D sda,sdb
dstat -n -N eth0,eth1
dstat -c -C total,0,1
----
You can show both the individual values and total values as follows:
----
[dag@horsea ~]$ dstat -d -D total,hda,hdc
-dsk/total----dsk/hda-----dsk/hdc--
read writ: read writ: read writ
1384k 1502k: 114k 1332k: 81k 359B
0 44k: 0 44k: 0 0
0 0 : 0 0 : 0 0
----
The special +-f+ or +--full+ option allows to select individual counters by
default, and can be overruled by +-C+, +-D+, +-I+, +-N+ or +-S+.
=== Influencing output
Dstat has a few more options to influence its output. With the +--nocolor+
one can disable colours. The +--noheaders+ option disables repeating headers.
The +--noupdate+ option disables intermediate updates. The +--output+ option
is used for writing out to a CSV file.
=== Plugin search path
Dstat looks in the following places for plugins. This allows a user without
root privileges to use some extra plugins.
- ~/.dstat/
- <binarypath>/plugins/
- /usr/share/dstat/
- /usr/local/share/dstat/
The option +--list+ shows the available plugins and their location in the
order that the plugin search path is used.
NOTE: Plugins are named +dstat_<name>.py+.
== Use-cases
Below are some use-cases to demonstrate the usage of Dstat.
WARNING: The following examples do not look as nice as they do on screen
because this document is not printed in colour (and I did not prepare it in
colour :-)).
=== Simple system check
Let's say you quickly want to see if the system is doing alright. In the past
this probably was a +vmstat 1+, as of now you would do:
----
dstat -taf
----
.Sample output
----
[dag@rhun dag]$ dstat -taf
-----time----- -------cpu0-usage------ --dsk/sda-----dsk/sr0-- --net/eth1- ---paging-- ---system--
date/time |usr sys idl wai hiq siq| read writ: read writ| recv send| in out | int csw
02-08 02:42:48| 10 2 85 2 0 0| 22k 23k: 1.8B 0 | 0 0 |2588B 2952B| 558 580
02-08 02:42:49| 4 3 93 0 0 0| 0 0 : 0 0 | 0 0 | 0 0 |1116 962
02-08 02:42:50| 5 2 90 0 2 1| 0 28k: 0 0 | 0 0 | 0 0 |1380 1136
02-08 02:42:51| 11 6 82 0 1 0| 0 0 : 0 0 | 0 0 | 0 0 |1277 1340
02-08 02:42:52| 3 3 93 0 1 0| 0 84k: 0 0 | 0 0 | 0 0 |1311 1034
----
NOTE: The +-t+ here is completely optional and generally wastes space. But
often you are not monitoring for 10 seconds but rather measure in minutes or
hours. Having a general idea on what timescale counters have been averaged is
nevertheless interesting.
=== What is this system doing now ?
I often run both the +dstat_top_cpu+ and +dstat_top_mem+ programs on a system,
just to see what a system is doing. Having a quick look at what application
is using the most CPU over a few minutes and to see what the general usage
of memory is of the top application gives away a lot about a system.
.Sample output
----
[dag@horsea dag]$ dstat -c --top-cpu -dng --top-mem
----total-cpu-usage---- -most-expensive- -dsk/total- -net/total- ---paging-- -most-expensive-
usr sys idl wai hiq siq| cpu process | read writ| recv send| in out | memory process
9 2 80 9 0 0|kswapd 0| 123k 164k| 0 0 |9196B 18k|rsync 74M
2 3 95 0 0 0|sendmail 1| 0 168k|2584B 39k| 0 0 |rsync 74M
18 3 79 0 0 0|httpd 17| 0 88k|5759B 118k| 0 0 |rsync 74M
3 2 94 1 0 0|sendmail 1|4096B 0 |2291B 4190B| 0 0 |rsync 74M
2 3 95 0 0 0|httpd 1| 0 0 |2871B 3201B| 0 0 |rsync 74M
10 7 83 0 0 0|httpd 13| 0 0 |2216B 10k| 0 0 |rsync 74M
2 2 96 0 0 0| | 0 52k| 724B 2674B| 0 0 |rsync 74M
----
=== What process is using all my CPU, memory or I/O at 4:20 AM ?
Imagine the monitoring team notices strange peaks, a system engineer got a
worthless message, the system was swapping extensively, a process got killed.
Something indicates the system is doing something unexpected but what is
causing it and why ? As of now you can do:
----
screen dstat -tcy --top-cpu 120
screen dstat -tmgs --top-mem 120
screen dstat -tdi --top-io 120
----
to see what process is using the most CPU, the most memory and the most I/O
resources.
And hopefully one day we can do:
----
dstat -tn --top-net 120
dstat -tn --top-x 120
----
Leave it running during the night and in the morning you can see the light.
=== What device is slowing down my system ?
Many devices generate interrupts, especially when used at maximum capacity.
Sometimes too many interrupts can slow down a system. If you want to correlate
bad performance with hardware interrupts, you can run a command like:
----
dstat -tyif
dstat -tyi -I 12,58,iwlagn -f 5
----
=== How much ticks per second on my kernel ?
In some cases it can be useful to see how many ticks (timer interrupts) your
kernel is producing. With older kernels this is a fixed number (usually 100,
250 or 1000) but on newer kernels the number can be dynamic.
Also on VMware virtual machines, the number of ticks can cause clock issues,
so in that case if you want to see what is happening, you can simply do:
----
dstat -ti -I0 --snooze --debug
----
Dstat nowadays can also detect lost ticks (when the number of ticks do not
match the time progress. This is useful to correlate VM issues with other
problems.
////
=== Monitoring memory consumption of a process over time
Now, I have twice used Dstat to verify memory usage. And I have concluded that
2 programs have severe memory leaks. One, unsurprisingly, is Firefox, the
other sadly is wnck-applet (yes, unfortunately).
Now Dstat is currently not really useful for specifying your own process to
monitor (unless you dig into the module, which is easier than one might
expect). But I am already anticipating Pstat, which is a Dstat but for
process-related counters.
More on this later...
////
=== What device is slowing down my system ?
A nice feature of Dstat is that it can show how many interrupts each of your
devices is generating. The 'cpu' stats already show this in percentage as
'hard interrupt' and 'soft interrupt', and the 'sys' stats shows the total
number of interrupts, but the 'int' stats go into detail. And you can specify
exactly what IRQs you want to watch.
Much like +watch -n1 -d cat /proc/interrupts+ on steroids.
----
dstat -t -y -i -f
----
which then results in:
.Sample output
----
[dag@rhun ~]$ dstat -t -y -i -f 5
-----time----- ---system-- -------------------interrupts------------------
date/time | int csw | 1 9 12 14 15 58 177 185
13-08 21:52:53| 740 923 | 1 0 18 5 1 17 4 131
13-08 21:52:58|1491 2085 | 0 4 351 1 2 37 0 97
13-08 21:53:03|1464 1981 | 0 0 332 1 3 31 0 96
13-08 21:53:08|1343 1977 | 0 0 215 1 2 32 0 93
13-08 21:53:13|1145 1918 | 0 0 12 0 3 33 0 95
----
When having the following hardware:
----
[dag@rhun ~]$ cat /proc/interrupts
CPU0
0: 143766685 IO-APIC-edge timer
1: 374043 IO-APIC-edge i8042
9: 102564 IO-APIC-level acpi
12: 4481057 IO-APIC-edge i8042
14: 1192508 IO-APIC-edge libata
15: 358891 IO-APIC-edge libata
58: 4391819 IO-APIC-level ipw2200
177: 993740 IO-APIC-level Intel ICH6
185: 33542364 IO-APIC-level yenta, uhci_hcd:usb1, eth0, i915@pci:0000:00:02.0
NMI: 0
LOC: 143766578
ERR: 0
MIS: 0
----
Or select specific interrupts:
----
dstat -t -y -i -I 12,58,185 -f 5
----
=== How does my WIFI signal evolve when I move my laptop or AP through the house ?
Something I was looking into when trying to find the optimal location for the
WIFI access point. However I must say that another tool I wrote 'Dwscan' is
currently more sophisticated.
----
dstat -t --wifi
----
=== Is my SWRAID performing as it claims ?
You can monitor I/O throughput for any block device. By default dstat limits
itself to real block devices to prevent having the same I/O to be counted more
than once, but if you want to monitor a SWRAID device, or a multipath device,
you can simply do that by doing:
----
dstat -td -D md0,md1,sda,sdb,hda
----
== Writing your own Dstat plugin
Dstat is completely written in python and this makes it extremely convenient
to write your own plugins. The many plugins that come with Dstat are an
excellent source of information if you want to write your own.
=== Introducing the hello world plugin
The following plugin does nothing more than write "Hello world!" to its
output.
.The dstat_helloworld plugin in its full glory.
----
class dstat_helloworld(dstat):
def __init__(self):
self.name = 'plugin title' <1>
self.type = 's' <2>
self.width = 12 <3>
self.scale = 100 <4>
self.nick = ('counter',) <5>
self.vars = ('text',) <6>
self.init(self.vars, 1) <7>
def extract(self):
self.val['text'] = 'Hello world!' <8>
----
In this example, there are several components:
. +self.name+ contains the plugin's visible title.
. +self.type+ defines the counter type: string, percentage, integer, float
. +self.width+ defines the column width
. +self.scale+ influences the coloring and unit type
. +self.nick+ is a list of the counter names
. +self.vars+ is a list of the variable names for each counter
. +self.init()+ is a function that initialises the counter structures
(+self.cn1+, +self.cn2+ and +self.val+)
. +self.val+ contains the counter values that are being displayed
=== Parsing counters
The following example shows how information is collected and counters are
processed. It also includes a +check()+ method to properly bail out when the
system fails to meet some plugin criteria.
.The dstat_postfix plugin
----
global glob <1>
import glob
class dstat_postfix(dstat):
def __init__(self):
self.name = 'postfix'
self.type = 'd' <2>
self.width = 4
self.scale = 100
self.vars = ('incoming', 'active', 'deferred', 'bounce', 'defer')
self.nick = ('inco', 'actv', 'dfrd', 'bnce', 'defr')
self.init(self.vars, 1)
def check(self): <3>
if not os.access('/var/spool/postfix/active', os.R_OK):
raise Exception, 'Cannot access postfix queues'
return True
def extract(self):
for item in self.vars: <4>
self.val[item] = len(glob.glob('/var/spool/postfix/'+item+'/*/*')
----
This example shows the following items:
. Since the plugin is imported at runtime, it is important that these are
are included in the global scope to reuse them
. type, width and scale specify decimal, column width a,d coloring based on
multiplication of 100
. The +check()+ method tests conditions and bails out of they are not met
. To make processing easier we have opted to use as value names (+self.vars+)
the name of the postfix queues and store counts in +self.val+
=== Opening files
Dstat provides its own +dopen()+ function to plugins. Using +dopen()+ instead
of +open()+ plugins do not need to reopen files to update their counters. But
this is only useful when plugins open a few files. For eg. opening _/proc/pid_
files the number of open files would only be increasing as the number of
processes increases.
=== Piping to an application
Dstat provides its own +dpopen()+ function to plugins. This function allows
the plugin to open stdin, stdout and stderr pipes for 2-way communication with
processes. To see this in action, take a look at the +dstat_gpfs+ plugins or
the +dstat_mysql+ plugins.
Piping to an application is more expensive than getting kernel counters from
_/proc_, but it beats having to run a program and capturing the output.
== Known issues
There are some known issues that are important to understand when using Dstat.
=== Counter rollovers
Unfortunately Dstat is susceptible for counters that ``rollover''. This means
that a counter gets bigger than its maximum value the data-structure is capable
of storing. As a result the counter is reset.
For some architectures and some counters, Linux implements 32bit values, this
means that such counter can go up to 2^32 (= 4294967296B = 4G) values.
For example the network counters are calculated in absolute bytes. Every 4GB
that is being transferred over the network will cause a counter reset. For
example on a bonded 2x10Gbps interfaces that is using its theoretical transfer
limit, this would happen every 1.6 seconds.
Since _/proc_ is updated every second, this would be impossible for Dstat to
catch. Currently if Dstat encounters a negative difference for an interval it
displays a dash.
Obviously, if Dstat were know what the counter's maximum value is, it could
recalculate the difference. However that is currently not implemented and does
not guarantee a correct result either, since a negative value could be the
result of 2 or more rollovers.
If you suspect that the behaviour of your system is susceptible of counter
rollovers, make sure you take this into account when using Dstat (or any other
tool that uses these counters for that matter)
TIP: Shipped with the Dstat documentation there is a document
(_counter-rollovers.txt_) that goes deeper into counter rollovers. If this
affects you, read that document and contact me for possible implementation
changes to improve handling them.
=== Dstat performance
As mentioned several times now, Dstat is written in python. There are various
reasons that Python was chosen and the most important reason is that it
simplifies writing plugins, processing counters and lowers the bar for
people to contribute changes.
The downside of choosing a scripting language is that it is slower than if it
would be written in C, obviously. *Dstat is not optimised for performance.*
NOTE: This may seem ironic: a performance monitoring tool that is not
optimised for performance, but rather for flexibility. However the ease of
writing plugins and prototyping gets precedence over performance at this time.
==== Plugin performance
If we look at the basic plugins, there are no real performance issues with
Dstat. Loading Dstat takes longer than eg. vmstat, but once running, Dstat's
performance for the same functionality is up to par with vmstat, ifstat and
other similar tools.
However there are plugins that are much more resource intensive than others
and the selection of plugins determines Dstat's performance in a major way.
==== Debugging Dstat
Dstat comes with a +--debug+ option that helps to find the cost of running
plugins. The +--debug+ option show how long it takes Dstat to process the
selected plugins.
You can see the cost of Dstat itself by simply using the +dstat_time+ plugin
together with the +--debug+ option.
.The cost of running the timer plugin
----
[dag@rhun dag]$ dstat -t --debug
Module dstat_time
-----time-----
date/time
19-08 20:34:21 5.90ms
19-08 20:34:22 0.17ms
19-08 20:34:23 0.18ms
19-08 20:34:24 0.18ms
----
Compare this with other plugins to see what the cost is of an individual
plugin.
.The cost of running the +dstat_cpu+ plugin
----
[dag@rhun dstat]$ dstat -c --debug
Module dstat_cpu requires ['/proc/stat']
----total-cpu-usage----
usr sys idl wai hiq siq
15 3 77 4 0 1 11.07ms
5 3 92 0 0 0 0.66ms
5 4 91 0 0 0 0.65ms
5 3 92 0 0 0 0.66ms
----
As you can see, getting the CPU counters and calculating the CPU usage takes
up 0.5 milliseconds on this particular system. But if we look at the usage of
the +dstat_top_cpu+ plugin:
.The cost of running the +dstat_top_cpu+ plugin
----
[dag@rhun dstat]$ dstat --top-cpu --debug
Module dstat_top_cpu
-most-expensive-
cpu process
Xorg 2 43.82ms
Xorg 1 33.23ms
firefox-bin 2 33.54ms
Xorg 1 33.24ms
----
we see that processing the _/proc/pid_ files causes the top-cpu plugin to use
an additional 33ms.
WARNING: These values show the time it takes to process the plugins and does
not indicate the amount of CPU usage Dstat consumes. This obviously means that
the process time of plugins depends on how much the system is being stressed
as well as on what the plugin exactly is doing.
Plugins that communicate with other processes or those that process lots of
information (eg. communicating with the mysql client, or processing the mail
queue) may not actually use any local resources, but the latency causes
Dstat to slow down processing other counters.
==== Writing Dstat and plugins in C
It makes sense to reimplement Dstat or some of its plugins in C and still
allow the writing of Python (or even Perl) plugins. Tests have shown that for
example processing _/proc/pid_ in C makes the plugin 3 times faster. And this
did not take into account the processing of the results and displaying the
output.
So rewriting in C makes a lot of sense, but it is also much more complicated.
=== Python 1.5
Dstat works with python 2.0, however there is also a Dstat15 version that
still works on python 1.5. The downside of having Dstat work on python 1.5 is
that the external plugins cannot use the newer and more flexible python 2.0
syntax and the differences between python 1.5 and 2.0 are considerable.
NOTE: Not all plugins work properly on Python 1.5.
== Future development
The Dstat release contains a _TODO_ file highlighting all the items and
ideas that have been played with. Here is a list of the most important ones:
- Output
* Changes in how Dstat colours digits within a value (the 6 in 6134B)
*
- Exporting information
* Connecting Dstat with rrdtool
* Exporting to syslog or remote syslog (a way to transport counters ?)
- Plugins
* Be smart when plugins are loaded more than once (some plugins could
benefit)
* Add more plugins
- Redesign Dstat
* Work on the plugin infrastructure, make the API more simple and
straightforward
* Create an object-model and namespace for plugins and counters so that
other tools can be based on Dstat
== Links
- http://dag.wieers.com/home-made/dstat/[Dstat homepage]
- http://svn.rpmforge.net/svn/trunk/tools/dstat/[Dstat subversion]
- http://lists.rpmforge.net/mailman/listinfo/tools[Dstat mailinglist]
// vim: set syntax=asciidoc:
<file_sep>/rs-sysmon2/plugins/dstat_fan.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Fan speed in RPM (rotations per minute) as reported by ACPI.
"""
def __init__(self):
self.name = 'fan'
self.type = 'd'
self.width = 4
self.scale = 500
self.open('/proc/acpi/ibm/fan')
def vars(self):
ret = None
for l in self.splitlines():
if l[0] == 'speed:':
ret = ('speed',)
return ret
def check(self):
if not os.path.exists('/proc/acpi/ibm/fan'):
raise Exception, 'Needs kernel IBM-ACPI support'
def extract(self):
if os.path.exists('/proc/acpi/ibm/fan'):
for l in self.splitlines():
if l[0] == 'speed:':
self.val['speed'] = int(l[1])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_disk_util.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Percentage of bandwidth utilization for block devices.
Displays percentage of CPU time during which I/O requests were issued
to the device (bandwidth utilization for the device). Device saturation
occurs when this value is close to 100%.
"""
def __init__(self):
self.nick = ('util', )
self.type = 'f'
self.width = 4
self.scale = 34
self.diskfilter = re.compile('^(dm-\d+|md\d+|[hsv]d[a-z]+\d+)$')
self.open('/proc/diskstats')
self.cols = 1
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 13: continue
if l[3:] == ['0',] * 11: continue
name = l[2]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception, "No suitable block devices found to monitor"
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
if name not in blockdevices(): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover:
ret.append(name)
return ret
def name(self):
return [sysfs_dev(name) for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, )
for l in self.splitlines():
if len(l) < 13: continue
if l[5] == '0' and l[9] == '0': continue
name = l[2]
if l[3:] == ['0',] * 11: continue
if name in self.vars:
self.set2[name] = ( self.set2[name][0] + long(l[12]), )
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 1.0 * hz / elapsed / 1000,
)
if step == op.delay:
self.set1.update(self.set2)
<file_sep>/rs-sysmon2/plugins/dstat_squid.py
### Authority: <NAME> <<EMAIL>>
# This plugin has been tested with:
# - Dstat 0.6.7
# - CentOS release 5.4 (Final)
# - Python 2.4.3
# - Squid 2.6 and 2.7
global squidclient_options
squidclient_options = os.getenv('DSTAT_SQUID_OPTS') # -p 8080
class dstat_plugin(dstat):
'''
Provides various Squid statistics.
'''
def __init__(self):
self.name = 'squid status'
self.type = 's'
self.width = 5
self.scale = 1000
self.vars = ('Number of file desc currently in use',
'CPU Usage, 5 minute avg',
'Total accounted',
'Number of clients accessing cache',
'Mean Object Size')
self.nick = ('fdesc',
'cpu5',
'mem',
'clnts',
'objsz')
def check(self):
if not os.access('/usr/sbin/squidclient', os.X_OK):
raise Exception, 'Needs squidclient binary'
cmd_test('/usr/sbin/squidclient %s mgr:info' % squidclient_options)
return True
def extract(self):
try:
for l in cmd_splitlines('/usr/sbin/squidclient %s mgr:info' % squidclient_options, ':'):
if l[0].strip() in self.vars:
self.val[l[0].strip()] = l[1].strip()
break
except IOError, e:
if op.debug > 1: print '%s: lost pipe to squidclient, %s' % (self.filename, e)
for name in self.vars: self.val[name] = -1
except Exception, e:
if op.debug > 1: print '%s: exception' (self.filename, e)
for name in self.vars: self.val[name] = -1
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_nfs3_ops.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'extended nfs3 client operations'
self.nick = ('null', 'gatr', 'satr', 'look', 'aces', 'rdln', 'read', 'writ', 'crea', 'mkdr', 'syml', 'mknd', 'rm', 'rmdr', 'ren', 'link', 'rdir', 'rdr+', 'fstt', 'fsnf', 'path', 'cmmt')
self.vars = ('null', 'getattr', 'setattr', 'lookup', 'access', 'readlink', 'read', 'write', 'create', 'mkdir', 'symlink', 'mknod', 'remove', 'rmdir', 'rename', 'link', 'readdir', 'readdirplus', 'fsstat', 'fsinfo', 'pathconf', 'commit')
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/net/rpc/nfs')
def check(self):
info(1, 'Module %s is still experimental.') % self.filename
def extract(self):
for l in self.splitlines():
if not l or l[0] != 'proc3': continue
for i, name in enumerate(self.vars):
self.set2[name] = long(l[i+2])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_dstat_mem.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Provide memory information related to the dstat process.
The various values provide information about the memory usage of the
dstat process. This plugin gives you the possibility to follow memory
usage changes of dstat over time. It may help to vizualise the
performance of Dstat and its selection of plugins.
"""
def __init__(self):
self.name = 'dstat memory usage'
self.vars = ('virtual', 'resident', 'shared', 'data')
self.type = 'd'
self.open('/proc/%s/statm' % ownpid)
def extract(self):
l = self.splitline()
# l = linecache.getline('/proc/%s/schedstat' % self.pid, 1).split()
self.val['virtual'] = long(l[0]) * pagesize / 1024
self.val['resident'] = long(l[1]) * pagesize / 1024
self.val['shared'] = long(l[2]) * pagesize / 1024
# self.val['text'] = long(l[3]) * pagesize / 1024
# self.val['library'] = long(l[4]) * pagesize / 1024
self.val['data'] = long(l[5]) * pagesize / 1024
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_innodb_io.py
### Author: <NAME> <<EMAIL>>
global mysql_options
mysql_options = os.getenv('DSTAT_MYSQL')
class dstat_plugin(dstat):
def __init__(self):
self.name = 'innodb io ops '
self.nick = ('rea', 'wri', 'syn')
self.vars = ('read', 'write', 'sync')
self.type = 'f'
self.width = 3
self.scale = 1000
def check(self):
if os.access('/usr/bin/mysql', os.X_OK):
try:
self.stdin, self.stdout, self.stderr = dpopen('/usr/bin/mysql -n %s' % mysql_options)
except IOError:
raise Exception, 'Cannot interface with MySQL binary'
return True
raise Exception, 'Needs MySQL binary'
def extract(self):
try:
self.stdin.write('show engine innodb status\G\n')
line = greppipe(self.stdout, 'OS file reads ')
if line:
l = line.split()
self.set2['read'] = l[0].rstrip(',')
self.set2['write'] = l[4].rstrip(',')
self.set2['sync'] = l[8]
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
except IOError, e:
if op.debug > 1: print '%s: lost pipe to mysql, %s' % (self.filename, e)
for name in self.vars: self.val[name] = -1
except Exception, e:
if op.debug > 1: print '%s: exception' % (self.filename, e)
for name in self.vars: self.val[name] = -1
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_gpfs.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Total amount of read and write throughput (in bytes) on a GPFS filesystem.
"""
def __init__(self):
self.name = 'gpfs i/o'
self.nick = ('read', 'write')
self.vars = ('_br_', '_bw_')
def check(self):
if os.access('/usr/lpp/mmfs/bin/mmpmon', os.X_OK):
try:
self.stdin, self.stdout, self.stderr = dpopen('/usr/lpp/mmfs/bin/mmpmon -p -s')
self.stdin.write('reset\n')
readpipe(self.stdout)
except IOError:
raise Exception, 'Cannot interface with gpfs mmpmon binary'
return True
raise Exception, 'Needs GPFS mmpmon binary'
def extract(self):
try:
self.stdin.write('io_s\n')
# readpipe(self.stderr)
for line in readpipe(self.stdout):
if not line: continue
l = line.split()
for name in self.vars:
self.set2[name] = long(l[l.index(name)+1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
except IOError, e:
if op.debug > 1: print '%s: lost pipe to mmpmon, %s' % (self.filename, e)
for name in self.vars: self.val[name] = -1
except Exception, e:
if op.debug > 1: print '%s: exception %s' % (self.filename, e)
for name in self.vars: self.val[name] = -1
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_freespace.py
### Author: <NAME> <<EMAIL>>
### FIXME: This module needs infrastructure to provide a list of mountpoints
### FIXME: Would be nice to have a total by default (half implemented)
class dstat_plugin(dstat):
"""
Amount of used and free space per mountpoint.
"""
def __init__(self):
self.nick = ('used', 'free')
self.open('/etc/mtab')
self.cols = 2
def vars(self):
ret = []
for l in self.splitlines():
if len(l) < 6: continue
if l[2] in ('binfmt_misc', 'devpts', 'iso9660', 'none', 'proc', 'sysfs', 'usbfs'): continue
### FIXME: Excluding 'none' here may not be what people want (/dev/shm)
if l[0] in ('devpts', 'none', 'proc', 'sunrpc', 'usbfs'): continue
name = l[1]
res = os.statvfs(name)
if res[0] == 0: continue ### Skip zero block filesystems
ret.append(name)
return ret
def name(self):
return ['/' + os.path.basename(name) for name in self.vars]
def extract(self):
self.val['total'] = (0, 0)
for name in self.vars:
res = os.statvfs(name)
self.val[name] = ( (float(res.f_blocks) - float(res.f_bavail)) * long(res.f_frsize), float(res.f_bavail) * float(res.f_frsize) )
self.val['total'] = (self.val['total'][0] + self.val[name][0], self.val['total'][1] + self.val[name][1])
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/dstat
#!/usr/bin/env python
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU Library General Public License as published by
### the Free Software Foundation; version 2 only
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
### GNU Library General Public License for more details.
###
### You should have received a copy of the GNU Library General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
### Copyright 2004-2007 <NAME> <<EMAIL>>
from __future__ import generators
try:
import sys, os, time, sched, re, getopt
import types, resource, getpass, glob, linecache
except KeyboardInterrupt:
pass
VERSION = '0.7.2'
theme = { 'default': '' }
if sys.version_info < (2, 2):
sys.exit('error: Python 2.2 or later required')
### Workaround for python <= 2.2.1
try:
True, False
except NameError:
True = 1
False = 0
### Workaround for python < 2.3
#if 'enumerate' not in __builtins__.__dict__.keys():
if sys.version_info >= (2, 2) and sys.version_info < (2, 3):
def enumerate(sequence):
index = 0
for item in sequence:
yield index, item
index = index + 1
elif sys.version_info < (2, 2):
def enumerate(sequence):
index = 0
seqlist = []
for item in sequence:
seqlist.append((index, item))
index = index + 1
return seqlist
### Workaround for python < 2.3
#if 'sum' not in __builtins__.__dict__.keys():
if sys.version_info < (2, 3):
def sum(sequence):
ret = 0
for i in sequence:
ret = ret + i
return ret
pluginpath = [
os.path.expanduser('~/.dstat/'), # home + /.dstat/
os.path.abspath(os.path.dirname(sys.argv[0])) + '/plugins/', # binary path + /plugins/
'/usr/share/dstat/',
'/usr/local/share/dstat/',
]
class Options:
def __init__(self, args):
self.args = args
self.blackonwhite = False
self.count = -1
self.cpulist = None
self.debug = 0
self.delay = 1
self.disklist = None
self.full = False
self.float = False
self.integer = False
self.intlist = None
self.netlist = None
self.swaplist = None
self.color = True
self.update = True
self.header = True
self.output = False
self.pidfile = False
self.profile = ''
### List of available plugins
allplugins = listplugins()
### List of plugins to show
self.plugins = []
### Implicit if no terminal is used
if not sys.stdout.isatty():
self.color = False
self.header = False
self.update = False
### Temporary hardcoded for my own project
self.diskset = {
'local': ('sda', 'hd[a-d]'),
'lores': ('sd[b-k]', 'sd[v-z]', 'sda[a-e]'),
'hires': ('sd[l-u]', 'sda[f-o]'),
}
try:
opts, args = getopt.getopt(args, 'acdfghilmno:prstTvyC:D:I:M:N:S:V',
['all', 'all-plugins', 'bw', 'blackonwhite', 'debug',
'filesystem', 'float', 'full', 'help', 'integer',
'list', 'mods', 'modules', 'nocolor', 'noheaders', 'noupdate',
'output=', 'pidfile=', 'profile', 'version', 'vmstat'] + allplugins)
except getopt.error, exc:
print 'dstat: %s, try dstat -h for a list of all the options' % str(exc)
sys.exit(1)
for opt, arg in opts:
if opt in ['-c']:
self.plugins.append('cpu')
elif opt in ['-C']:
self.cpulist = arg.split(',')
elif opt in ['-d']:
self.plugins.append('disk')
elif opt in ['-D']:
self.disklist = arg.split(',')
elif opt in ['--filesystem']:
self.plugins.append('fs')
elif opt in ['-g']:
self.plugins.append('page')
elif opt in ['-i']:
self.plugins.append('int')
elif opt in ['-I']:
self.intlist = arg.split(',')
elif opt in ['-l']:
self.plugins.append('load')
elif opt in ['-m']:
self.plugins.append('mem')
elif opt in ['-M', '--mods', '--modules']:
print >>sys.stderr, 'WARNING: Option %s is deprecated, please use --%s instead' % (opt, ' --'.join(arg.split(',')))
self.plugins += arg.split(',')
elif opt in ['-n']:
self.plugins.append('net')
elif opt in ['-N']:
self.netlist = arg.split(',')
elif opt in ['-p']:
self.plugins.append('proc')
elif opt in ['-r']:
self.plugins.append('io')
elif opt in ['-s']:
self.plugins.append('swap')
elif opt in ['-S']:
self.swaplist = arg.split(',')
elif opt in ['-t']:
self.plugins.append('time')
elif opt in ['-T']:
self.plugins.append('epoch')
elif opt in ['-y']:
self.plugins.append('sys')
elif opt in ['-a', '--all']:
self.plugins += [ 'cpu', 'disk', 'net', 'page', 'sys' ]
elif opt in ['-v', '--vmstat']:
self.plugins += [ 'proc', 'mem', 'page', 'disk', 'sys', 'cpu' ]
elif opt in ['-f', '--full']:
self.full = True
elif opt in ['--all-plugins']:
### Make list unique in a fancy fast way
plugins = {}.fromkeys(allplugins).keys()
plugins.sort()
self.plugins += plugins
elif opt in ['--bw', '--black-on-white']:
self.blackonwhite = True
elif opt in ['--debug']:
self.debug = self.debug + 1
elif opt in ['--float']:
self.float = True
elif opt in ['--integer']:
self.integer = True
elif opt in ['--list']:
showplugins()
sys.exit(0)
elif opt in ['--nocolor']:
self.color = False
self.update = False
elif opt in ['--noheaders']:
self.header = False
elif opt in ['--noupdate']:
self.update = False
elif opt in ['-o', '--output']:
self.output = arg
elif opt in ['--pidfile']:
self.pidfile = arg
elif opt in ['--profile']:
self.profile = 'dstat_profile.log'
elif opt in ['-h', '--help']:
self.usage()
self.help()
sys.exit(0)
elif opt in ['-V', '--version']:
self.version()
sys.exit(0)
elif opt.startswith('--'):
self.plugins.append(opt[2:])
else:
print 'dstat: option %s unknown to getopt, try dstat -h for a list of all the options' % opt
sys.exit(1)
if self.float and self.integer:
print 'dstat: option --float and --integer are mutual exlusive, you can only force one'
sys.exit(1)
if not self.plugins:
print 'You did not select any stats, using -cdngy by default.'
self.plugins = [ 'cpu', 'disk', 'net', 'page', 'sys' ]
try:
if len(args) > 0: self.delay = int(args[0])
if len(args) > 1: self.count = int(args[1])
except:
print 'dstat: incorrect argument, try dstat -h for the correct syntax'
sys.exit(1)
if self.delay <= 0:
print 'dstat: delay must be an integer, greater than zero'
sys.exit(1)
def version(self):
print 'Dstat %s' % VERSION
print 'Written by <NAME> <<EMAIL>>'
print 'Homepage at http://dag.wieers.com/home-made/dstat/'
print
print 'Platform %s/%s' % (os.name, sys.platform)
print 'Kernel %s' % os.uname()[2]
print 'Python %s' % sys.version
print
color = ""
if not gettermcolor(self.color):
color = "no "
print 'Terminal type: %s (%scolor support)' % (os.getenv('TERM'), color)
rows, cols = gettermsize()
print 'Terminal size: %d lines, %d columns' % (rows, cols)
print
print 'Processors: %d' % getcpunr()
print 'Pagesize: %d' % resource.getpagesize()
print 'Clock ticks per secs: %d' % os.sysconf('SC_CLK_TCK')
print
global op
op = self
showplugins()
def usage(self):
print 'Usage: dstat [-afv] [options..] [delay [count]]'
def help(self):
print '''Versatile tool for generating system resource statistics
Dstat options:
-c, --cpu enable cpu stats
-C 0,3,total include cpu0, cpu3 and total
-d, --disk enable disk stats
-D total,hda include hda and total
-g, --page enable page stats
-i, --int enable interrupt stats
-I 5,eth2 include int5 and interrupt used by eth2
-l, --load enable load stats
-m, --mem enable memory stats
-n, --net enable network stats
-N eth1,total include eth1 and total
-p, --proc enable process stats
-r, --io enable io stats (I/O requests completed)
-s, --swap enable swap stats
-S swap1,total include swap1 and total
-t, --time enable time/date output
-T, --epoch enable time counter (seconds since epoch)
-y, --sys enable system stats
--aio enable aio stats
--fs, --filesystem enable fs stats
--ipc enable ipc stats
--lock enable lock stats
--raw enable raw stats
--socket enable socket stats
--tcp enable tcp stats
--udp enable udp stats
--unix enable unix stats
--vm enable vm stats
--plugin-name enable plugins by plugin name (see manual)
--list list all available plugins
-a, --all equals -cdngy (default)
-f, --full automatically expand -C, -D, -I, -N and -S lists
-v, --vmstat equals -pmgdsc -D total
--float force float values on screen
--integer force integer values on screen
--bw, --blackonwhite change colors for white background terminal
--nocolor disable colors (implies --noupdate)
--noheaders disable repetitive headers
--noupdate disable intermediate updates
--output file write CSV output to file
delay is the delay in seconds between each update (default: 1)
count is the number of updates to display before exiting (default: unlimited)
'''
### START STATS DEFINITIONS ###
class dstat:
vars = None
name = None
nick = None
type = 'f'
width = 5
scale = 1024
cols = 0
# val = {}
# set1 = {}
# set2 = {}
def prepare(self):
if callable(self.discover):
self.discover = self.discover()
if callable(self.vars):
self.vars = self.vars()
if not self.vars:
raise Exception, 'No counter objects to monitor'
if callable(self.name):
self.name = self.name()
if callable(self.nick):
self.nick = self.nick()
if not self.nick:
self.nick = self.vars
self.val = {}; self.set1 = {}; self.set2 = {}
if self.cols <= 0:
for name in self.vars:
self.val[name] = self.set1[name] = self.set2[name] = 0
else:
for name in self.vars + [ 'total', ]:
self.val[name] = range(self.cols)
self.set1[name] = range(self.cols)
self.set2[name] = range(self.cols)
for i in range(self.cols):
self.val[name][i] = self.set1[name][i] = self.set2[name][i] = 0
# print self.val
def open(self, *filenames):
"Open stat file descriptor"
self.file = []
self.fd = []
for filename in filenames:
try:
fd = dopen(filename)
if fd:
self.file.append(filename)
self.fd.append(fd)
except:
pass
if not self.fd:
raise Exception, 'Cannot open file %s' % filename
def readlines(self):
"Return lines from any file descriptor"
for fd in self.fd:
fd.seek(0)
for line in fd.readlines():
yield line
### Implemented linecache (for top-plugins) but slows down normal plugins
# for fd in self.fd:
# i = 1
# while True:
# line = linecache.getline(fd.name, i);
# if not line: break
# yield line
# i += 1
def splitline(self, sep=None):
for fd in self.fd:
fd.seek(0)
return fd.read().split(sep)
def splitlines(self, sep=None, replace=None):
"Return split lines from any file descriptor"
for fd in self.fd:
fd.seek(0)
for line in fd.readlines():
if replace and sep:
yield line.replace(replace, sep).split(sep)
elif replace:
yield line.replace(replace, ' ').split()
else:
yield line.split(sep)
# ### Implemented linecache (for top-plugins) but slows down normal plugins
# for fd in self.fd:
# if replace and sep:
# yield line.replace(replace, sep).split(sep)
# elif replace:
# yield line.replace(replace, ' ').split()
# else:
# yield line.split(sep)
# i += 1
def statwidth(self):
"Return complete stat width"
if self.cols:
return len(self.vars) * self.colwidth() + len(self.vars) - 1
else:
return len(self.nick) * self.colwidth() + len(self.nick) - 1
def colwidth(self):
"Return column width"
if isinstance(self.name, types.StringType):
return self.width
else:
return len(self.nick) * self.width + len(self.nick) - 1
def title(self):
ret = theme['title']
if isinstance(self.name, types.StringType):
width = self.statwidth()
return ret + self.name[0:width].center(width).replace(' ', '-') + theme['default']
for i, name in enumerate(self.name):
width = self.colwidth()
ret = ret + name[0:width].center(width).replace(' ', '-')
if i + 1 != len(self.name):
if op.color:
ret = ret + theme['frame'] + char['dash'] + theme['title']
else:
ret = ret + char['space']
return ret
def subtitle(self):
ret = ''
if isinstance(self.name, types.StringType):
for i, nick in enumerate(self.nick):
ret = ret + theme['subtitle'] + nick[0:self.width].center(self.width) + theme['default']
if i + 1 != len(self.nick): ret = ret + char['space']
return ret
else:
for i, name in enumerate(self.name):
for j, nick in enumerate(self.nick):
ret = ret + theme['subtitle'] + nick[0:self.width].center(self.width) + theme['default']
if j + 1 != len(self.nick): ret = ret + char['space']
if i + 1 != len(self.name): ret = ret + theme['frame'] + char['colon']
return ret
def csvtitle(self):
if isinstance(self.name, types.StringType):
return '"' + self.name + '"' + ',' * (len(self.nick) - 1)
else:
ret = ''
for i, name in enumerate(self.name):
ret = ret + '"' + name + '"' + ',' * (len(self.nick) - 1)
if i + 1 != len(self.name): ret = ret + ','
return ret
def csvsubtitle(self):
ret = ''
if isinstance(self.name, types.StringType):
for i, nick in enumerate(self.nick):
ret = ret + '"' + nick + '"'
if i + 1 != len(self.nick): ret = ret + ','
return ret
else:
for i, name in enumerate(self.name):
for j, nick in enumerate(self.nick):
ret = ret + '"' + nick + '"'
if j + 1 != len(self.nick): ret = ret + ','
if i + 1 != len(self.name): ret = ret + ','
return ret
def check(self):
"Check if stat is applicable"
# if hasattr(self, 'fd') and not self.fd:
# raise Exception, 'File %s does not exist' % self.fd
if not self.vars:
raise Exception, 'No objects found, no stats available'
if not self.discover:
raise Exception, 'No objects discovered, no stats available'
if self.colwidth():
return True
raise Exception, 'Unknown problem, please report'
def discover(self, *objlist):
return True
def show(self):
"Display stat results"
line = ''
if hasattr(self, 'output'):
return cprint(self.output, self.type, self.width, self.scale)
for i, name in enumerate(self.vars):
if isinstance(self.val[name], types.TupleType) or isinstance(self.val[name], types.ListType):
line = line + cprintlist(self.val[name], self.type, self.width, self.scale)
sep = theme['frame'] + char['colon']
else:
line = line + cprint(self.val[name], self.type, self.width, self.scale)
sep = char['space']
if i + 1 != len(self.vars):
line = line + sep
return line
def showend(self, totlist, vislist):
if self is not vislist[-1]:
return theme['frame'] + char['pipe']
elif totlist != vislist:
return theme['frame'] + char['gt']
return ''
def showcsv(self):
def printcsv(var):
if var != round(var):
return '%.3f' % var
return '%s' % round(var)
line = ''
for i, name in enumerate(self.vars):
if isinstance(self.val[name], types.ListType) or isinstance(self.val[name], types.TupleType):
for j, val in enumerate(self.val[name]):
line = line + printcsv(val)
if j + 1 != len(self.val[name]):
line = line + ','
elif isinstance(self.val[name], types.StringType):
line = line + self.val[name]
else:
line = line + printcsv(self.val[name])
if i + 1 != len(self.vars):
line = line + ','
return line
def showcsvend(self, totlist, vislist):
if self is not vislist[-1]:
return ','
elif self is not totlist[-1]:
return ','
return ''
class dstat_aio(dstat):
def __init__(self):
self.name = 'async'
self.nick = ('#aio',)
self.vars = ('aio',)
self.type = 'd'
self.width = 5;
self.open('/proc/sys/fs/aio-nr')
def extract(self):
for l in self.splitlines():
if len(l) < 1: continue
self.val['aio'] = long(l[0])
class dstat_cpu(dstat):
def __init__(self):
self.nick = ( 'usr', 'sys', 'idl', 'wai', 'hiq', 'siq' )
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/stat')
self.cols = 6
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 8 or l[0][0:3] != 'cpu': continue
ret.append(l[0][3:])
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.cpulist:
varlist = op.cpulist
elif not op.full:
varlist = ('total',)
else:
varlist = []
cpu = 0
while cpu < cpunr:
varlist.append(str(cpu))
cpu = cpu + 1
# if len(varlist) > 2: varlist = varlist[0:2]
for name in varlist:
if name in self.discover + ['total']:
ret.append(name)
return ret
def name(self):
ret = []
for name in self.vars:
if name == 'total':
ret.append('total cpu usage')
else:
ret.append('cpu' + name + ' usage')
return ret
def extract(self):
for l in self.splitlines():
if len(l) < 8: continue
for name in self.vars:
if l[0] == 'cpu' + name or ( l[0] == 'cpu' and name == 'total' ):
self.set2[name] = ( long(l[1]) + long(l[2]), long(l[3]), long(l[4]), long(l[5]), long(l[6]), long(l[7]) )
for name in self.vars:
for i in range(6):
if sum(self.set2[name]) > sum(self.set1[name]):
self.val[name][i] = 100.0 * (self.set2[name][i] - self.set1[name][i]) / (sum(self.set2[name]) - sum(self.set1[name]))
else:
self.val[name][i] = 0
# print >>sys.stderr, "Error: tick problem detected, this should never happen !"
if step == op.delay:
self.set1.update(self.set2)
class dstat_cpu24(dstat):
def __init__(self):
self.nick = ( 'usr', 'sys', 'idl')
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/stat')
self.cols = 3
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) != 5 or l[0][0:3] != 'cpu': continue
ret.append(l[0][3:])
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.cpulist:
varlist = op.cpulist
elif not op.full:
varlist = ('total',)
else:
varlist = []
cpu = 0
while cpu < cpunr:
varlist.append(str(cpu))
cpu = cpu + 1
# if len(varlist) > 2: varlist = varlist[0:2]
for name in varlist:
if name in self.discover + ['total']:
ret.append(name)
return ret
def name(self):
ret = []
for name in self.vars:
if name == 'total':
ret.append('cpu usage')
else:
ret.append('cpu' + name)
return ret
def extract(self):
for l in self.splitlines():
for name in self.vars:
if l[0] == 'cpu' + name or ( l[0] == 'cpu' and name == 'total' ):
self.set2[name] = ( long(l[1]) + long(l[2]), long(l[3]), long(l[4]) )
for name in self.vars:
for i in range(3):
self.val[name][i] = 100.0 * (self.set2[name][i] - self.set1[name][i]) / (sum(self.set2[name]) - sum(self.set1[name]))
if step == op.delay:
self.set1.update(self.set2)
class dstat_disk(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'd'
self.diskfilter = re.compile('^(dm-\d+|md\d+|[hsv]d[a-z]+\d+)$')
self.open('/proc/diskstats')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 13: continue
if l[3:] == ['0',] * 11: continue
name = l[2]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception, "No suitable block devices found to monitor"
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
if name not in blockdevices(): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] + op.diskset.keys():
ret.append(name)
return ret
def name(self):
return ['dsk/'+sysfs_dev(name) for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for l in self.splitlines():
if len(l) < 13: continue
if l[5] == '0' and l[9] == '0': continue
name = l[2]
if l[3:] == ['0',] * 11: continue
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[5]), self.set2['total'][1] + long(l[9]) )
if name in self.vars and name != 'total':
self.set2[name] = ( self.set2[name][0] + long(l[5]), self.set2[name][1] + long(l[9]) )
for diskset in self.vars:
if diskset in op.diskset.keys():
for disk in op.diskset[diskset]:
if re.match('^'+disk+'$', name):
self.set2[diskset] = ( self.set2[diskset][0] + long(l[5]), self.set2[diskset][1] + long(l[9]) )
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 512.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 512.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
class dstat_disk24(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'd'
self.diskfilter = re.compile('(dm-\d+|md\d+|[hsv]d[a-z]+\d+)')
self.open('/proc/partitions')
if self.fd and not self.discover:
raise Exception, 'Kernel is not compiled with CONFIG_BLK_STATS'
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 15 or l[0] == 'major' or int(l[1]) % 16 != 0: continue
name = l[3]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception, "No suitable block devices found to monitor"
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] + op.diskset.keys():
ret.append(name)
return ret
def name(self):
return ['dsk/'+sysfs_dev(name) for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for l in self.splitlines():
if len(l) < 15 or l[0] == 'major' or int(l[1]) % 16 != 0: continue
name = l[3]
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[6]), self.set2['total'][1] + long(l[10]) )
if name in self.vars:
self.set2[name] = ( self.set2[name][0] + long(l[6]), self.set2[name][1] + long(l[10]) )
for diskset in self.vars:
if diskset in op.diskset.keys():
for disk in op.diskset[diskset]:
if re.match('^'+disk+'$', name):
self.set2[diskset] = ( self.set2[diskset][0] + long(l[6]), self.set2[diskset][1] + long(l[10]) )
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 512.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 512.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
### FIXME: Needs rework, does anyone care ?
class dstat_disk24old(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'd'
self.diskfilter = re.compile('(dm-\d+|md\d+|[hsv]d[a-z]+\d+)')
self.regexp = re.compile('^\((\d+),(\d+)\):\(\d+,\d+,(\d+),\d+,(\d+)\)$')
self.open('/proc/stat')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines(':'):
if len(l) < 3: continue
name = l[0]
if name != 'disk_io': continue
for pair in line.split()[1:]:
m = self.regexp.match(pair)
if not m: continue
l = m.groups()
if len(l) < 4: continue
name = dev(int(l[0]), int(l[1]))
ret.append(name)
break
for item in objlist: ret.append(item)
if not ret:
raise Exception, "No suitable block devices found to monitor"
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] + op.diskset.keys():
ret.append(name)
return ret
def name(self):
return ['dsk/'+name for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for line in self.splitlines(':'):
if len(l) < 3: continue
name = l[0]
if name != 'disk_io': continue
for pair in line.split()[1:]:
m = self.regexp.match(pair)
if not m: continue
l = m.groups()
if len(l) < 4: continue
name = dev(int(l[0]), int(l[1]))
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[2]), self.set2['total'][1] + long(l[3]) )
if name in self.vars and name != 'total':
self.set2[name] = ( self.set2[name][0] + long(l[2]), self.set2[name][1] + long(l[3]) )
for diskset in self.vars:
if diskset in op.diskset.keys():
for disk in op.diskset[diskset]:
if re.match('^'+disk+'$', name):
self.set2[diskset] = ( self.set2[diskset][0] + long(l[2]), self.set2[diskset][1] + long(l[3]) )
break
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 512.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 512.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
class dstat_epoch(dstat):
def __init__(self):
self.name = 'epoch'
self.vars = ('epoch',)
self.width = 10
if op.debug:
self.width = 13
self.scale = 0
### We are now using the starttime instead of the execution time of this plugin
def extract(self):
# self.val['epoch'] = time.time()
self.val['epoch'] = starttime
class dstat_fs(dstat):
def __init__(self):
self.name = 'filesystem'
self.vars = ('files', 'inodes')
self.type = 'd'
self.width = 6
self.scale = 1000
def extract(self):
for line in dopen('/proc/sys/fs/file-nr'):
l = line.split()
if len(l) < 1: continue
self.val['files'] = long(l[0])
for line in dopen('/proc/sys/fs/inode-nr'):
l = line.split()
if len(l) < 2: continue
self.val['inodes'] = long(l[0]) - long(l[1])
class dstat_int(dstat):
def __init__(self):
self.name = 'interrupts'
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/stat')
self.intmap = self.intmap()
def intmap(self):
ret = {}
for line in dopen('/proc/interrupts'):
l = line.split()
if len(l) <= cpunr: continue
l1 = l[0].split(':')[0]
l2 = ' '.join(l[cpunr+2:]).split(',')
ret[l1] = l1
for name in l2:
ret[name.strip().lower()] = l1
return ret
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if l[0] != 'intr': continue
for name, i in enumerate(l[2:]):
if long(i) > 10: ret.append(str(name))
return ret
# def check(self):
# if self.fd[0] and self.vars:
# self.fd[0].seek(0)
# for l in self.fd[0].splitlines():
# if l[0] != 'intr': continue
# return True
# return False
def vars(self):
ret = []
if op.intlist:
varlist = op.intlist
else:
varlist = self.discover
for name in varlist:
if name in ('0', '1', '2', '8', 'NMI', 'LOC', 'MIS', 'CPU0'):
varlist.remove(name)
if not op.full and len(varlist) > 3: varlist = varlist[-3:]
for name in varlist:
if name in self.discover + ['total',]:
ret.append(name)
elif name.lower() in self.intmap.keys():
ret.append(self.intmap[name.lower()])
return ret
def extract(self):
for l in self.splitlines():
if not l or l[0] != 'intr': continue
for name in self.vars:
if name != 'total':
self.set2[name] = long(l[int(name) + 2])
self.set2['total'] = long(l[1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
class dstat_int24(dstat):
def __init__(self):
self.name = 'interrupts'
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/interrupts')
def intmap(self):
ret = {}
for l in self.splitlines():
if len(l) <= cpunr: continue
l1 = l[0].split(':')[0]
l2 = ' '.join(l[cpunr+2:]).split(',')
ret[l1] = l1
for name in l2:
ret[name.strip().lower()] = l1
return ret
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < cpunr+1: continue
name = l[0].split(':')[0]
if long(l[1]) > 10:
ret.append(name)
return ret
# def check(self):
# if self.fd and self.discover:
# self.fd[0].seek(0)
# for l in self.fd[0].splitlines():
# if l[0] != 'intr' or len(l) > 2: continue
# return True
# return False
def vars(self):
ret = []
if op.intlist:
varlist = op.intlist
else:
varlist = self.discover
for name in varlist:
if name in ('0', '1', '2', '8', 'CPU0', 'ERR', 'LOC', 'MIS', 'NMI'):
varlist.remove(name)
if not op.full and len(varlist) > 3: varlist = varlist[-3:]
for name in varlist:
if name in self.discover:
ret.append(name)
elif name.lower() in self.intmap.keys():
ret.append(self.intmap[name.lower()])
return ret
def extract(self):
for l in self.splitlines():
if len(l) < cpunr+1: continue
name = l[0].split(':')[0]
if name in self.vars:
self.set2[name] = 0
for i in l[1:1+cpunr]:
self.set2[name] = self.set2[name] + long(i)
# elif len(l) > 2 + cpunr:
# for hw in self.vars:
# for mod in l[2+cpunr:]:
# self.set2[mod] = long(l[1])
for name in self.set2.keys():
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
class dstat_io(dstat):
def __init__(self):
self.nick = ('read', 'writ')
self.type = 'f'
self.width = 5
self.scale = 1000
self.diskfilter = re.compile('(dm-\d+|md\d+|[hsv]d[a-z]+\d+)')
self.open('/proc/diskstats')
self.cols = 3
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 13: continue
if l[3:] == ['0',] * 11: continue
name = l[2]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception, "No suitable block devices found to monitor"
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
if name not in blockdevices(): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] + op.diskset.keys():
ret.append(name)
return ret
def name(self):
return ['io/'+name for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for l in self.splitlines():
if len(l) < 13: continue
if l[3] == '0' and l[7] == '0': continue
name = l[2]
if l[3:] == ['0',] * 11: continue
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[3]), self.set2['total'][1] + long(l[7]) )
if name in self.vars and name != 'total':
self.set2[name] = ( self.set2[name][0] + long(l[3]), self.set2[name][1] + long(l[7]) )
for diskset in self.vars:
if diskset in op.diskset.keys():
for disk in op.diskset[diskset]:
if re.match('^'+disk+'$', name):
self.set2[diskset] = ( self.set2[diskset][0] + long(l[3]), self.set2[diskset][1] + long(l[7]) )
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 1.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 1.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
class dstat_ipc(dstat):
def __init__(self):
self.name = 'sysv ipc'
self.vars = ('msg', 'sem', 'shm')
self.type = 'd'
self.width = 3
self.scale = 10
def extract(self):
for name in self.vars:
self.val[name] = len(dopen('/proc/sysvipc/'+name).readlines()) - 1
class dstat_load(dstat):
def __init__(self):
self.name = 'load avg'
self.nick = ('1m', '5m', '15m')
self.vars = ('load1', 'load5', 'load15')
self.type = 'f'
self.width = 4
self.scale = 0.5
self.open('/proc/loadavg')
def extract(self):
for l in self.splitlines():
if len(l) < 3: continue
self.val['load1'] = float(l[0])
self.val['load5'] = float(l[1])
self.val['load15'] = float(l[2])
class dstat_lock(dstat):
def __init__(self):
self.name = 'file locks'
self.nick = ('pos', 'lck', 'rea', 'wri')
self.vars = ('posix', 'flock', 'read', 'write')
self.type = 'f'
self.width = 3
self.scale = 10
self.open('/proc/locks')
def extract(self):
for name in self.vars: self.val[name] = 0
for l in self.splitlines():
if len(l) < 4: continue
if l[1] == 'POSIX': self.val['posix'] += 1
elif l[1] == 'FLOCK': self.val['flock'] += 1
if l[3] == 'READ': self.val['read'] += 1
elif l[3] == 'WRITE': self.val['write'] += 1
class dstat_mem(dstat):
def __init__(self):
self.name = 'memory usage'
self.nick = ('used', 'buff', 'cach', 'free')
self.vars = ('MemUsed', 'Buffers', 'Cached', 'MemFree')
self.open('/proc/meminfo')
def extract(self):
for l in self.splitlines():
if len(l) < 2: continue
name = l[0].split(':')[0]
if name in self.vars + ('MemTotal', ):
self.val[name] = long(l[1]) * 1024.0
self.val['MemUsed'] = self.val['MemTotal'] - self.val['MemFree'] - self.val['Buffers'] - self.val['Cached']
class dstat_net(dstat):
def __init__(self):
self.nick = ('recv', 'send')
self.type = 'd'
self.totalfilter = re.compile('^(lo|bond\d+|face|.+\.\d+)$')
self.open('/proc/net/dev')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines(replace=':'):
if len(l) < 17: continue
if l[2] == '0' and l[10] == '0': continue
name = l[0]
if name not in ('lo', 'face'):
ret.append(name)
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.netlist:
varlist = op.netlist
elif not op.full:
varlist = ('total',)
else:
varlist = self.discover
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total', 'lo']:
ret.append(name)
if not ret:
raise Exception, "No suitable network interfaces found to monitor"
return ret
def name(self):
return ['net/'+name for name in self.vars]
def extract(self):
self.set2['total'] = [0, 0]
for l in self.splitlines(replace=':'):
if len(l) < 17: continue
if l[2] == '0' and l[10] == '0': continue
name = l[0]
if name in self.vars :
self.set2[name] = ( long(l[1]), long(l[9]) )
if not self.totalfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[1]), self.set2['total'][1] + long(l[9]))
if update:
for name in self.set2.keys():
self.val[name] = [
(self.set2[name][0] - self.set1[name][0]) * 1.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 1.0 / elapsed,
]
if self.val[name][0] < 0: self.val[name][0] += maxint + 1
if self.val[name][1] < 0: self.val[name][1] += maxint + 1
if step == op.delay:
self.set1.update(self.set2)
class dstat_page(dstat):
def __init__(self):
self.name = 'paging'
self.nick = ('in', 'out')
self.vars = ('pswpin', 'pswpout')
self.type = 'd'
self.open('/proc/vmstat')
def extract(self):
for l in self.splitlines():
if len(l) < 2: continue
name = l[0]
if name in self.vars:
self.set2[name] = long(l[1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * pagesize * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
class dstat_page24(dstat):
def __init__(self):
self.name = 'paging'
self.nick = ('in', 'out')
self.vars = ('pswpin', 'pswpout')
self.type = 'd'
self.open('/proc/stat')
def extract(self):
for l in self.splitlines():
if len(l) < 3: continue
name = l[0]
if name != 'swap': continue
self.set2['pswpin'] = long(l[1])
self.set2['pswpout'] = long(l[2])
break
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * pagesize * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
class dstat_proc(dstat):
def __init__(self):
self.name = 'procs'
self.nick = ('run', 'blk', 'new')
self.vars = ('procs_running', 'procs_blocked', 'processes')
self.type = 'f'
self.width = 3
self.scale = 10
self.open('/proc/stat')
def extract(self):
for l in self.splitlines():
if len(l) < 2: continue
name = l[0]
if name == 'processes':
self.val['processes'] = 0
self.set2[name] = long(l[1])
elif name == 'procs_running':
self.set2[name] = self.set2[name] + long(l[1]) - 1
elif name == 'procs_blocked':
self.set2[name] = self.set2[name] + long(l[1])
self.val['processes'] = (self.set2['processes'] - self.set1['processes']) * 1.0 / elapsed
for name in ('procs_running', 'procs_blocked'):
self.val[name] = self.set2[name] * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
for name in ('procs_running', 'procs_blocked'):
self.set2[name] = 0
class dstat_raw(dstat):
def __init__(self):
self.name = 'raw'
self.nick = ('raw',)
self.vars = ('sockets',)
self.type = 'd'
self.width = 3
self.scale = 100
self.open('/proc/net/raw')
def extract(self):
lines = -1
for line in self.readlines():
lines += 1
self.val['sockets'] = lines
### Cannot use len() on generator
# self.val['sockets'] = len(self.readlines()) - 1
class dstat_socket(dstat):
def __init__(self):
self.name = 'sockets'
self.type = 'd'
self.width = 3
self.scale = 100
self.open('/proc/net/sockstat')
self.nick = ('tot', 'tcp', 'udp', 'raw', 'frg')
self.vars = ('sockets:', 'TCP:', 'UDP:', 'RAW:', 'FRAG:')
def extract(self):
for l in self.splitlines():
if len(l) < 3: continue
self.val[l[0]] = long(l[2])
self.val['other'] = self.val['sockets:'] - self.val['TCP:'] - self.val['UDP:'] - self.val['RAW:'] - self.val['FRAG:']
class dstat_swap(dstat):
def __init__(self):
self.name = 'swap'
self.nick = ('used', 'free')
self.type = 'd'
self.open('/proc/swaps')
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 5: continue
if l[0] == 'Filename': continue
try:
int(l[2])
int(l[3])
except:
continue
# ret.append(improve(l[0]))
ret.append(l[0])
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.swaplist:
varlist = op.swaplist
elif not op.full:
varlist = ('total',)
else:
varlist = self.discover
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total']:
ret.append(name)
if not ret:
raise Exception, "No suitable swap devices found to monitor"
return ret
def name(self):
return ['swp/'+improve(name) for name in self.vars]
def extract(self):
self.val['total'] = [0, 0]
for l in self.splitlines():
if len(l) < 5 or l[0] == 'Filename': continue
name = l[0]
self.val[name] = ( long(l[3]) * 1024.0, (long(l[2]) - long(l[3])) * 1024.0 )
self.val['total'] = ( self.val['total'][0] + self.val[name][0], self.val['total'][1] + self.val[name][1])
class dstat_swapold(dstat):
def __init__(self):
self.name = 'swap'
self.nick = ('used', 'free')
self.vars = ('SwapUsed', 'SwapFree')
self.type = 'd'
self.open('/proc/meminfo')
def extract(self):
for l in self.splitlines():
if len(l) < 2: continue
name = l[0].split(':')[0]
if name in self.vars + ('SwapTotal',):
self.val[name] = long(l[1]) * 1024.0
self.val['SwapUsed'] = self.val['SwapTotal'] - self.val['SwapFree']
class dstat_sys(dstat):
def __init__(self):
self.name = 'system'
self.nick = ('int', 'csw')
self.vars = ('intr', 'ctxt')
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/stat')
def extract(self):
for l in self.splitlines():
if len(l) < 2: continue
name = l[0]
if name in self.vars:
self.set2[name] = long(l[1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
class dstat_tcp(dstat):
def __init__(self):
self.name = 'tcp sockets'
self.nick = ('lis', 'act', 'syn', 'tim', 'clo')
self.vars = ('listen', 'established', 'syn', 'wait', 'close')
self.type = 'd'
self.width = 3
self.scale = 100
self.open('/proc/net/tcp', '/proc/net/tcp6')
def extract(self):
for name in self.vars: self.val[name] = 0
for l in self.splitlines():
if len(l) < 12: continue
### 01: established, 02: syn_sent, 03: syn_recv, 04: fin_wait1,
### 05: fin_wait2, 06: time_wait, 07: close, 08: close_wait,
### 09: last_ack, 0A: listen, 0B: closing
if l[3] in ('0A',): self.val['listen'] += 1
elif l[3] in ('01',): self.val['established'] += 1
elif l[3] in ('02', '03', '09',): self.val['syn'] += 1
elif l[3] in ('06',): self.val['wait'] += 1
elif l[3] in ('04', '05', '07', '08', '0B',): self.val['close'] += 1
class dstat_time(dstat):
def __init__(self):
self.name = 'system'
self.timefmt = os.getenv('DSTAT_TIMEFMT') or '%d-%m %H:%M:%S'
self.type = 's'
if op.debug:
self.width = len(time.strftime(self.timefmt, time.localtime())) + 4
else:
self.width = len(time.strftime(self.timefmt, time.localtime()))
self.scale = 0
self.vars = ('time',)
### We are now using the starttime for this plugin, not the execution time of this plugin
def extract(self):
if op.debug:
self.val['time'] = time.strftime(self.timefmt, time.localtime(starttime)) + ".%03d" % (round(starttime * 1000 % 1000 ))
else:
self.val['time'] = time.strftime(self.timefmt, time.localtime(starttime))
class dstat_udp(dstat):
def __init__(self):
self.name = 'udp'
self.nick = ('lis', 'act')
self.vars = ('listen', 'established')
self.type = 'd'
self.width = 3
self.scale = 100
self.open('/proc/net/udp', '/proc/net/udp6')
def extract(self):
for name in self.vars: self.val[name] = 0
for l in self.splitlines():
if l[3] == '07': self.val['listen'] += 1
elif l[3] == '01': self.val['established'] += 1
class dstat_unix(dstat):
def __init__(self):
self.name = 'unix sockets'
self.nick = ('dgm', 'str', 'lis', 'act')
self.vars = ('datagram', 'stream', 'listen', 'established')
self.type = 'd'
self.width = 3
self.scale = 100
self.open('/proc/net/unix')
def extract(self):
for name in self.vars: self.val[name] = 0
for l in self.splitlines():
if l[4] == '0002': self.val['datagram'] += 1
elif l[4] == '0001':
self.val['stream'] += 1
if l[5] == '01': self.val['listen'] += 1
elif l[5] == '03': self.val['established'] += 1
class dstat_vm(dstat):
def __init__(self):
self.name = 'virtual memory'
self.nick = ('majpf', 'minpf', 'alloc', 'free')
self.vars = ('pgmajfault', 'pgfault', 'pgalloc', 'pgfree')
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/vmstat')
### Page allocations should include all page zones, not just ZONE_NORMAL,
### but also ZONE_DMA, ZONE_HIGHMEM, ZONE_DMA32 (depending on architecture)
def extract(self):
self.set2['pgalloc'] = 0
for l in self.splitlines():
if len(l) < 2: continue
if l[0].startswith('pgalloc_'):
self.set2['pgalloc'] += long(l[1])
elif l[0] in self.vars:
self.set2[l[0]] = long(l[1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
### END STATS DEFINITIONS ###
ansi = {
'black': '\033[0;30m',
'darkred': '\033[0;31m',
'darkgreen': '\033[0;32m',
'darkyellow': '\033[0;33m',
'darkblue': '\033[0;34m',
'darkmagenta': '\033[0;35m',
'darkcyan': '\033[0;36m',
'gray': '\033[0;37m',
'darkgray': '\033[1;30m',
'red': '\033[1;31m',
'green': '\033[1;32m',
'yellow': '\033[1;33m',
'blue': '\033[1;34m',
'magenta': '\033[1;35m',
'cyan': '\033[1;36m',
'white': '\033[1;37m',
'blackbg': '\033[40m',
'redbg': '\033[41m',
'greenbg': '\033[42m',
'yellowbg': '\033[43m',
'bluebg': '\033[44m',
'magentabg': '\033[45m',
'cyanbg': '\033[46m',
'whitebg': '\033[47m',
'reset': '\033[0;0m',
'bold': '\033[1m',
'reverse': '\033[2m',
'underline': '\033[4m',
'clear': '\033[2J',
# 'clearline': '\033[K',
'clearline': '\033[2K',
# 'save': '\033[s',
# 'restore': '\033[u',
'save': '\0337',
'restore': '\0338',
'linewrap': '\033[7h',
'nolinewrap': '\033[7l',
'up': '\033[1A',
'down': '\033[1B',
'right': '\033[1C',
'left': '\033[1D',
'default': '\033[0;0m',
}
char = {
'pipe': '|',
'colon': ':',
'gt': '>',
'space': ' ',
'dash': '-',
'plus': '+',
}
def set_theme():
"Provide a set of colors to use"
if op.blackonwhite:
theme = {
'title': ansi['darkblue'],
'subtitle': ansi['darkcyan'] + ansi['underline'],
'frame': ansi['darkblue'],
'default': ansi['default'],
'error': ansi['white'] + ansi['redbg'],
'roundtrip': ansi['darkblue'],
'debug': ansi['darkred'],
'input': ansi['darkgray'],
'text_lo': ansi['black'],
'text_hi': ansi['darkgray'],
'unit_lo': ansi['black'],
'unit_hi': ansi['darkgray'],
'colors_lo': (ansi['darkred'], ansi['darkmagenta'], ansi['darkgreen'], ansi['darkblue'],
ansi['darkcyan'], ansi['gray'], ansi['red'], ansi['green']),
'colors_hi': (ansi['red'], ansi['magenta'], ansi['green'], ansi['blue'],
ansi['cyan'], ansi['white'], ansi['darkred'], ansi['darkgreen']),
}
else:
theme = {
'title': ansi['darkblue'],
'subtitle': ansi['blue'] + ansi['underline'],
'frame': ansi['darkblue'],
'default': ansi['default'],
'error': ansi['white'] + ansi['redbg'],
'roundtrip': ansi['darkblue'],
'debug': ansi['darkred'],
'input': ansi['darkgray'],
'text_lo': ansi['gray'],
'text_hi': ansi['darkgray'],
'unit_lo': ansi['darkgray'],
'unit_hi': ansi['darkgray'],
'colors_lo': (ansi['red'], ansi['yellow'], ansi['green'], ansi['blue'],
ansi['cyan'], ansi['white'], ansi['darkred'], ansi['darkgreen']),
'colors_hi': (ansi['darkred'], ansi['darkyellow'], ansi['darkgreen'], ansi['darkblue'],
ansi['darkcyan'], ansi['gray'], ansi['red'], ansi['green']),
}
return theme
def ticks():
"Return the number of 'ticks' since bootup"
try:
for line in open('/proc/uptime', 'r', 0).readlines():
l = line.split()
if len(l) < 2: continue
return float(l[0])
except:
for line in dopen('/proc/stat').readlines():
l = line.split()
if len(l) < 2: continue
if l[0] == 'btime':
return time.time() - long(l[1])
def improve(devname):
"Improve a device name"
if devname.startswith('/dev/mapper/'):
devname = devname.split('/')[3]
elif devname.startswith('/dev/'):
devname = devname.split('/')[2]
return devname
def dopen(filename):
"Open a file for reuse, if already opened, return file descriptor"
global fds
if not os.path.exists(filename):
raise Exception, 'File %s does not exist' % filename
# return None
if 'fds' not in globals().keys():
fds = {}
if file not in fds.keys():
fds[filename] = open(filename, 'r', 0)
else:
fds[filename].seek(0)
return fds[filename]
def dclose(filename):
"Close an open file and remove file descriptor from list"
global fds
if not 'fds' in globals().keys(): fds = {}
if filename in fds:
fds[filename].close()
del(fds[filename])
def dpopen(cmd):
"Open a pipe for reuse, if already opened, return pipes"
global pipes, select
import select
if 'pipes' not in globals().keys(): pipes = {}
if cmd not in pipes.keys():
pipes[cmd] = os.popen3(cmd, 't', 0)
return pipes[cmd]
def readpipe(fileobj, tmout = 0.001):
"Read available data from pipe in a non-blocking fashion"
ret = ''
while not select.select([fileobj.fileno()], [], [], tmout)[0]:
pass
while select.select([fileobj.fileno()], [], [], tmout)[0]:
ret = ret + fileobj.read(1)
return ret.split('\n')
def greppipe(fileobj, str, tmout = 0.001):
"Grep available data from pipe in a non-blocking fashion"
ret = ''
while not select.select([fileobj.fileno()], [], [], tmout)[0]:
pass
while select.select([fileobj.fileno()], [], [], tmout)[0]:
character = fileobj.read(1)
if character != '\n':
ret = ret + character
elif ret.startswith(str):
return ret
else:
ret = ''
if op.debug:
raise Exception, 'Nothing found during greppipe data collection'
return None
def matchpipe(fileobj, string, tmout = 0.001):
"Match available data from pipe in a non-blocking fashion"
ret = ''
regexp = re.compile(string)
while not select.select([fileobj.fileno()], [], [], tmout)[0]:
pass
while select.select([fileobj.fileno()], [], [], tmout)[0]:
character = fileobj.read(1)
if character != '\n':
ret = ret + character
elif regexp.match(ret):
return ret
else:
ret = ''
if op.debug:
raise Exception, 'Nothing found during matchpipe data collection'
return None
def cmd_test(cmd):
pipes = os.popen3(cmd, 't', 0)
for line in pipes[2].readlines():
raise Exception, line.strip()
def cmd_readlines(cmd):
pipes = os.popen3(cmd, 't', 0)
for line in pipes[1].readlines():
yield line
def cmd_splitlines(cmd, sep=None):
pipes = os.popen3(cmd, 't', 0)
for line in pipes[1].readlines():
yield line.split(sep)
def proc_readlines(filename):
"Return the lines of a file, one by one"
# for line in open(filename).readlines():
# yield line
### Implemented linecache (for top-plugins)
i = 1
while True:
line = linecache.getline(filename, i);
if not line: break
yield line
i += 1
def proc_splitlines(filename, sep=None):
"Return the splitted lines of a file, one by one"
# for line in open(filename).readlines():
# yield line.split(sep)
### Implemented linecache (for top-plugins)
i = 1
while True:
line = linecache.getline(filename, i);
if not line: break
yield line.split(sep)
i += 1
def proc_readline(filename):
"Return the first line of a file"
# return open(filename).read()
return linecache.getline(filename, 1)
def proc_splitline(filename, sep=None):
"Return the first line of a file splitted"
# return open(filename).read().split(sep)
return linecache.getline(filename, 1).split(sep)
### FIXME: Should we cache this within every step ?
def proc_pidlist():
"Return a list of process IDs"
dstat_pid = str(os.getpid())
for pid in os.listdir('/proc/'):
try:
### Is it a pid ?
int(pid)
### Filter out dstat
if pid == dstat_pid: continue
yield pid
except ValueError:
continue
def dchg(var, width, base):
"Convert decimal to string given base and length"
c = 0
while True:
ret = str(long(round(var)))
if len(ret) <= width:
break
var = var / base
c = c + 1
else:
c = -1
return ret, c
def fchg(var, width, base):
"Convert float to string given scale and length"
c = 0
while True:
if var == 0:
ret = str('0')
break
# ret = repr(round(var))
# ret = repr(long(round(var, maxlen)))
ret = str(long(round(var, width)))
if len(ret) <= width:
i = width - len(ret) - 1
while i > 0:
ret = ('%%.%df' % i) % var
if len(ret) <= width and ret != str(long(round(var, width))):
break
i = i - 1
else:
ret = str(long(round(var)))
break
var = var / base
c = c + 1
else:
c = -1
return ret, c
def tchg(var, width):
"Convert time string to given length"
ret = '%2dh%02d' % (var / 60, var % 60)
if len(ret) > width:
ret = '%2dh' % (var / 60)
if len(ret) > width:
ret = '%2dd' % (var / 60 / 24)
if len(ret) > width:
ret = '%2dw' % (var / 60 / 24 / 7)
return ret
def cprintlist(varlist, type, width, scale):
"Return all columns color printed"
ret = sep = ''
for var in varlist:
ret = ret + sep + cprint(var, type, width, scale)
sep = ' '
return ret
def cprint(var, type = 'f', width = 4, scale = 1000):
"Color print one column"
base = 1000
if scale == 1024:
base = 1024
### Use units when base is exact 1000 or 1024
unit = False
if scale in (1000, 1024) and width >= len(str(base)):
unit = True
width = width - 1
### If this is a negative value, return a dash
if var < 0:
if unit:
return theme['error'] + '-'.rjust(width) + ' ' + theme['default']
else:
return theme['error'] + '-'.rjust(width) + theme['default']
if base == 1024:
units = ('B', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
else:
units = (' ', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
if step == op.delay:
colors = theme['colors_lo']
ctext = theme['text_lo']
cunit = theme['unit_lo']
else:
colors = theme['colors_hi']
ctext = theme['text_hi']
cunit = theme['unit_hi']
### Convert value to string given base and field-length
if op.integer and type in ('d', 'p', 'f'):
ret, c = dchg(var, width, base)
elif op.float and type in ('d', 'p', 'f'):
ret, c = fchg(var, width, base)
elif type in ('d', 'p'):
ret, c = dchg(var, width, base)
elif type in ('f'):
ret, c = fchg(var, width, base)
elif type in ('s'):
ret, c = str(var), ctext
elif type in ('t'):
ret, c = tchg(var, width), ctext
else:
raise Exception, 'Type %s not known to dstat.' % type
### Set the counter color
if ret == '0':
color = cunit
elif scale <= 0:
color = ctext
elif scale not in (1000, 1024):
color = colors[int(var/scale)%len(colors)]
elif type in ('p'):
color = colors[int(round(var)/scale)%len(colors)]
elif type in ('d', 'f'):
color = colors[c%len(colors)]
else:
color = ctext
### Justify value to left if string
if type in ('s',):
ret = color + ret.ljust(width)
else:
ret = color + ret.rjust(width)
### Add unit to output
if unit:
if c != -1 and round(var) != 0:
ret += cunit + units[c]
else:
ret += ' '
return ret
def header(totlist, vislist):
"Return the header for a set of module counters"
line = ''
### Process title
for o in vislist:
line += o.title()
if o is not vislist[-1]:
line += theme['frame'] + char['space']
elif totlist != vislist:
line += theme['title'] + char['gt']
line += '\n'
### Process subtitle
for o in vislist:
line += o.subtitle()
if o is not vislist[-1]:
line += theme['frame'] + char['pipe']
elif totlist != vislist:
line += theme['title'] + char['gt']
return line + '\n'
def csvheader(totlist):
"Return the CVS header for a set of module counters"
line = ''
### Process title
for o in totlist:
line = line + o.csvtitle()
if o is not totlist[-1]:
line = line + ','
line += '\n'
### Process subtitle
for o in totlist:
line = line + o.csvsubtitle()
if o is not totlist[-1]:
line = line + ','
return line + '\n'
def info(level, str):
"Output info message"
# if level <= op.verbose:
print >>sys.stderr, str
def die(ret, str):
"Print error and exit with errorcode"
print >>sys.stderr, str
exit(ret)
def initterm():
"Initialise terminal"
global termsize
### Unbuffered sys.stdout
# sys.stdout = os.fdopen(1, 'w', 0)
try:
global fcntl, struct, termios
import fcntl, struct, termios
termios.TIOCGWINSZ
except:
try:
curses.setupterm()
curses.tigetnum('lines'), curses.tigetnum('cols')
except:
pass
else:
termsize = None, 2
else:
termsize = None, 1
def gettermsize():
"Return the dynamic terminal geometry"
global termsize
# if not termsize[0] and not termsize[1]:
if not termsize[0]:
try:
if termsize[1] == 1:
s = struct.pack('HHHH', 0, 0, 0, 0)
x = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, s)
return struct.unpack('HHHH', x)[:2]
elif termsize[1] == 2:
curses.setupterm()
return curses.tigetnum('lines'), curses.tigetnum('cols')
else:
termsize = (int(os.environ['LINES']), int(os.environ['COLUMNS']))
except:
termsize = 25, 80
return termsize
def gettermcolor(color=True):
"Return whether the system can use colors or not"
if color and sys.stdout.isatty():
try:
import curses
curses.setupterm()
if curses.tigetnum('colors') < 0:
return False
except:
print >>sys.stderr, 'Color support is disabled, python-curses is not installed.'
return False
return color
### We only want to filter out paths, not ksoftirqd/1
def basename(name):
"Perform basename on paths only"
if name[0] in ('/', '.'):
return os.path.basename(name)
return name
def getnamebypid(pid, name):
"Return the name of a process by taking best guesses and exclusion"
ret = None
try:
# cmdline = open('/proc/%s/cmdline' % pid).read().split('\0')
cmdline = linecache.getline('/proc/%s/cmdline' % pid, 1).split('\0')
ret = basename(cmdline[0])
if ret in ('bash', 'csh', 'ksh', 'perl', 'python', 'ruby', 'sh'):
ret = basename(cmdline[1])
if ret.startswith('-'):
ret = basename(cmdline[-2])
if ret.startswith('-'): raise
if not ret: raise
except:
ret = basename(name)
return ret
def getcpunr():
"Return the number of CPUs in the system"
cpunr = -1
for line in dopen('/proc/stat').readlines():
if line[0:3] == 'cpu':
cpunr = cpunr + 1
if cpunr < 0:
raise Exception, "Problem finding number of CPUs in system."
return cpunr
def blockdevices():
### We have to replace '!' by '/' to support cciss!c0d0 type devices :-/
return [os.path.basename(filename).replace('!', '/') for filename in glob.glob('/sys/block/*')]
### FIXME: Add scsi support too and improve
def sysfs_dev(device):
"Convert sysfs device names into device names"
m = re.match('ide/host(\d)/bus(\d)/target(\d)/lun(\d)/disc', device)
if m:
l = m.groups()
# ide/host0/bus0/target0/lun0/disc -> 0 -> hda
# ide/host0/bus1/target0/lun0/disc -> 2 -> hdc
nr = int(l[1]) * 2 + int(l[3])
return 'hd' + chr(ord('a') + nr)
m = re.match('cciss/(c\dd\d)', device)
if m:
l = m.groups()
return l[0]
m = re.match('placeholder', device)
if m:
return 'sdX'
return device
def dev(maj, min):
"Convert major/minor pairs into device names"
ram = [1, ]
ide = [3, 22, 33, 34, 56, 57, 88, 89, 90, 91]
loop = [7, ]
scsi = [8, 65, 66, 67, 68, 69, 70, 71, 128, 129, 130, 131, 132, 133, 134, 135]
md = [9, ]
ida = [72, 73, 74, 75, 76, 77, 78, 79]
ubd = [98,]
cciss = [104,]
dm = [253,]
if maj in scsi:
disc = chr(ord('a') + scsi.index(maj) * 16 + min / 16)
part = min % 16
if not part: return 'sd%s' % disc
return 'sd%s%d' % (disc, part)
elif maj in ide:
disc = chr(ord('a') + ide.index(maj) * 2 + min / 64)
part = min % 64
if not part: return 'hd%s' % disc
return 'hd%s%d' % (disc, part)
elif maj in dm:
return 'dm-%d' % min
elif maj in md:
return 'md%d' % min
elif maj in loop:
return 'loop%d' % min
elif maj in ram:
return 'ram%d' % min
elif maj in cciss:
disc = cciss.index(maj) * 16 + min / 16
part = min % 16
if not part: return 'c0d%d' % disc
return 'c0d%dp%d' % (disc, part)
elif maj in ida:
cont = ida.index(maj)
disc = min / 16
part = min % 16
if not part: return 'ida%d-%d' % (cont, disc)
return 'ida%d-%d-%d' % (cont, disc, part)
elif maj in ubd:
disc = ubd.index(maj) * 16 + min / 16
part = min % 16
if not part: return 'ubd%d' % disc
return 'ubd%d-%d' % (disc, part)
else:
return 'dev%d-%d' % (maj, min)
#def mountpoint(dev):
# "Return the mountpoint of a mounted device/file"
# for entry in dopen('/etc/mtab').readlines():
# if entry:
# devlist = entry.split()
# if dev == devlist[0]:
# return devlist[1]
#def readfile(file):
# ret = ''
# for line in open(file,'r').readlines():
# ret = ret + line
# return ret
#cdef extern from "sched.h":
# struct sched_param:
# int sched_priority
# int sched_setscheduler(int pid, int policy,sched_param *p)
#
#SCHED_FIFO = 1
#
#def switchRTCPriority(nb):
# cdef sched_param sp
# sp.sched_priority = nb
# sched_setscheduler (0,SCHED_FIFO , &sp);
def listplugins():
plugins = []
remod = re.compile('dstat_(.+)$')
for filename in globals():
if filename.startswith('dstat_'):
plugins.append(remod.match(filename).groups()[0])
remod = re.compile('.+/dstat_(.+).py$')
for path in pluginpath:
for filename in glob.glob(path + '/dstat_*.py'):
plugins.append(remod.match(filename).groups()[0].replace('_', '-'))
plugins.sort()
return plugins
def showplugins():
rows, cols = gettermsize()
print 'internal:\n\t',
remod = re.compile('dstat_(.+)$')
plugins = []
for filename in globals():
if filename.startswith('dstat_'):
plugins.append(remod.match(filename).groups()[0].replace('_', '-'))
plugins.sort()
cols2 = cols - 8
for mod in plugins:
cols2 = cols2 - len(mod) - 2
if cols2 <= 0:
print '\n\t',
cols2 = cols - len(mod) - 10
if mod != plugins[-1]:
print mod+',',
print mod
remod = re.compile('.+/dstat_(.+).py$')
for path in pluginpath:
plugins = []
for filename in glob.glob(path + '/dstat_*.py'):
plugins.append(remod.match(filename).groups()[0].replace('_', '-'))
if not plugins: continue
plugins.sort()
cols2 = cols - 8
print '%s:\n\t' % os.path.abspath(path),
for mod in plugins:
cols2 = cols2 - len(mod) - 2
if cols2 <= 0:
print '\n\t',
cols2 = cols - len(mod) - 10
if mod != plugins[-1]:
print mod+',',
print mod
def exit(ret):
sys.stdout.write(ansi['reset'])
sys.stdout.flush()
if op.pidfile and os.path.exists(op.pidfile):
os.remove(op.pidfile)
if op.profile and os.path.exists(op.profile):
rows, cols = gettermsize()
import pstats
p = pstats.Stats(op.profile)
# p.sort_stats('name')
# p.print_stats()
p.sort_stats('cumulative').print_stats(rows - 13)
# p.sort_stats('time').print_stats(rows - 13)
# p.sort_stats('file').print_stats('__init__')
# p.sort_stats('time', 'cum').print_stats(.5, 'init')
# p.print_callees()
elif op.profile:
print >>sys.stderr, "No profiling data was found, maybe profiler was interrupted ?"
sys.exit(ret)
def main():
"Initialization of the program, terminal, internal structures"
global cpunr, hz, maxint, ownpid, pagesize
global ansi, theme, outputfile
global totlist, inittime
global update, missed
cpunr = getcpunr()
hz = os.sysconf('SC_CLK_TCK')
maxint = (sys.maxint + 1) * 2
ownpid = str(os.getpid())
pagesize = resource.getpagesize()
interval = 1
user = getpass.getuser()
hostname = os.uname()[1]
### Disable line-wrapping (does not work ?)
sys.stdout.write('\033[7l')
### Write term-title
if sys.stdout.isatty():
shell = os.getenv('XTERM_SHELL')
term = os.getenv('TERM')
if shell == '/bin/bash' and term and re.compile('(screen*|xterm*)').match(term):
sys.stdout.write('\033]0;(%s@%s) %s %s\007' % (user, hostname, os.path.basename(sys.argv[0]), ' '.join(op.args)))
### Check background color (rxvt)
### COLORFGBG="15;default;0"
# if os.environ['COLORFGBG'] and len(os.environ['COLORFGBG'].split(';')) >= 3:
# l = os.environ['COLORFGBG'].split(';')
# bg = int(l[2])
# if bg < 7:
# print 'Background is dark'
# else:
# print 'Background is light'
# else:
# print 'Background is unknown, assuming dark.'
### Check terminal capabilities
op.color = gettermcolor(op.color)
### Prepare CSV output file
if op.output:
if os.path.exists(op.output):
outputfile = open(op.output, 'a', 0)
outputfile.write('\n\n')
else:
outputfile = open(op.output, 'w', 0)
outputfile.write('"Dstat %s CSV output"\n' % VERSION)
outputfile.write('"Author:","<NAME> <<EMAIL>>",,,,"URL:","http://dag.wieers.com/home-made/dstat/"\n')
outputfile.write('"Host:","%s",,,,"User:","%s"\n' % (hostname, user))
outputfile.write('"Cmdline:","dstat %s",,,,"Date:","%s"\n\n' % (' '.join(op.args), time.strftime('%d %b %Y %H:%M:%S %Z', time.localtime())))
### Create pidfile
if op.pidfile:
try:
pidfile = open(op.pidfile, 'w', 0)
pidfile.write(str(os.getpid()))
pidfile.close()
except Exception, e:
print >>sys.stderr, 'Failed to create pidfile %s' % op.pidfile, e
op.pidfile = False
### Empty ansi and theme database if no colors are requested
if not op.color:
op.update = False
for key in ansi.keys():
ansi[key] = ''
for key in theme.keys():
theme[key] = ''
theme['colors_hi'] = (ansi['default'],)
theme['colors_lo'] = (ansi['default'],)
# print ansi['blackbg']
if not op.update:
interval = op.delay
### Build list of requested plugins
linewidth = 0
totlist = []
for plugin in op.plugins:
### Set up fallback lists
if plugin == 'cpu': mods = ( 'cpu', 'cpu24' )
elif plugin == 'disk': mods = ( 'disk', 'disk24', 'disk24old' )
elif plugin == 'int': mods = ( 'int', 'int24' )
elif plugin == 'page': mods = ( 'page', 'page24' )
elif plugin == 'swap': mods = ( 'swap', 'swapold' )
else: mods = ( plugin, )
for mod in mods:
pluginfile = 'dstat_' + mod.replace('-', '_')
try:
if pluginfile not in globals().keys():
import imp
fp, pathname, description = imp.find_module(pluginfile, pluginpath)
fp.close()
### TODO: Would using .pyc help with anything ?
### Try loading python plugin
if description[0] in ('.py', ):
execfile(pathname)
exec 'o = dstat_plugin(); del(dstat_plugin)'
o.filename = pluginfile
o.check()
o.prepare()
### Try loading C plugin (not functional yet)
elif description[0] == '.so':
exec 'import %s' % pluginfile
exec 'o = %s.new()' % pluginfile
o.check()
o.prepare()
# print dir(o)
# print o.__module__
# print o.name
else:
print >>sys.stderr, 'Module %s is of unknown type.' % pluginfile
else:
exec 'o = %s()' % pluginfile
o.check()
o.prepare()
# print o.__module__
except Exception, e:
if mod == mods[-1]:
print >>sys.stderr, 'Module %s failed to load. (%s)' % (pluginfile, e)
elif op.debug:
print >>sys.stderr, 'Module %s failed to load, trying another. (%s)' % (pluginfile, e)
if op.debug >= 3:
raise
# tb = sys.exc_info()[2]
continue
except:
print >>sys.stderr, 'Module %s caused unknown exception' % pluginfile
linewidth = linewidth + o.statwidth() + 1
totlist.append(o)
if op.debug:
print 'Module', pluginfile,
if hasattr(o, 'file'):
print 'requires', o.file,
print
break
if not totlist:
die(8, 'None of the stats you selected are available.')
if op.output:
outputfile.write(csvheader(totlist))
scheduler = sched.scheduler(time.time, time.sleep)
inittime = time.time()
update = 0
missed = 0
### Let the games begin
while update <= op.delay * op.count or op.count == -1:
scheduler.enterabs(inittime + update, 1, perform, (update,))
# scheduler.enter(1, 1, perform, (update,))
scheduler.run()
sys.stdout.flush()
update = update + interval
linecache.clearcache()
if op.update:
sys.stdout.write('\n')
def perform(update):
"Inner loop that calculates counters and constructs output"
global totlist, oldvislist, vislist, showheader, rows, cols
global elapsed, totaltime, starttime
global loop, step, missed
starttime = time.time()
loop = (update - 1 + op.delay) / op.delay
step = ((update - 1) % op.delay) + 1
### Get current time (may be different from schedule) for debugging
if not op.debug:
curwidth = 0
else:
if step == 1 or loop == 0:
totaltime = 0
curwidth = 8
### FIXME: This is temporary functionality, we should do this better
### If it takes longer than 500ms, than warn !
if loop != 0 and starttime - inittime - update > 1:
missed = missed + 1
return 0
### Initialise certain variables
if loop == 0:
elapsed = ticks()
rows, cols = 0, 0
vislist = []
oldvislist = []
showheader = True
else:
elapsed = step
### FIXME: Make this part smarter
if sys.stdout.isatty():
oldcols = cols
rows, cols = gettermsize()
### Trim object list to what is visible on screen
if oldcols != cols:
vislist = []
for o in totlist:
newwidth = curwidth + o.statwidth() + 1
if newwidth <= cols or ( vislist == totlist[:-1] and newwidth < cols ):
vislist.append(o)
curwidth = newwidth
### Check when to display the header
if op.header and rows >= 6:
if oldvislist != vislist:
showheader = True
elif step == 1 and loop % (rows - 1) == 0:
showheader = True
oldvislist = vislist
else:
vislist = totlist
### Prepare the colors for intermediate updates, last step in a loop is definitive
if step == op.delay:
theme['default'] = ansi['reset']
else:
theme['default'] = theme['text_lo']
### The first step is to show the definitive line if necessary
newline = ''
if op.update:
if step == 1 and update != 0:
newline = '\n' + ansi['reset'] + ansi['clearline'] + ansi['save']
elif loop != 0:
newline = ansi['restore']
### Display header
if showheader:
if loop == 0 and totlist != vislist:
print >>sys.stderr, 'Terminal width too small, trimming output.'
showheader = False
sys.stdout.write(newline)
newline = header(totlist, vislist)
### Calculate all objects (visible, invisible)
line = newline
oline = ''
for o in totlist:
o.extract()
if o in vislist:
line = line + o.show() + o.showend(totlist, vislist)
if op.output and step == op.delay:
oline = oline + o.showcsv() + o.showcsvend(totlist, vislist)
### Print stats
sys.stdout.write(line + theme['input'])
if op.output and step == op.delay:
outputfile.write(oline + '\n')
### Print debugging output
if op.debug:
totaltime = totaltime + (time.time() - starttime) * 1000.0
if loop == 0:
totaltime = totaltime * step
if op.debug == 1:
sys.stdout.write('%s%6.2fms%s' % (theme['roundtrip'], totaltime / step, theme['input']))
elif op.debug == 2:
sys.stdout.write('%s%6.2f %s%d:%d%s' % (theme['roundtrip'], totaltime / step, theme['debug'], loop, step, theme['input']))
elif op.debug > 2:
sys.stdout.write('%s%6.2f %s%d:%d:%d%s' % (theme['roundtrip'], totaltime / step, theme['debug'], loop, step, update, theme['input']))
if missed > 0:
# sys.stdout.write(' '+theme['error']+'= warn =')
sys.stdout.write(' ' + theme['error'] + 'missed ' + str(missed+1) + ' ticks' + theme['input'])
missed = 0
### Finish the line
if not op.update:
sys.stdout.write('\n')
### Main entrance
if __name__ == '__main__':
try:
initterm()
op = Options(sys.argv[1:])
theme = set_theme()
if op.profile:
import profile
if os.path.exists(op.profile):
os.remove(op.profile)
profile.run('main()', op.profile)
else:
main()
except KeyboardInterrupt, e:
if op.update:
sys.stdout.write('\n')
exit(0)
else:
op = Options('')
step = 1
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/examples/curstest
#!/usr/bin/python
import curses, sys
#c = curses.wrapper(s)
#w = curses.initscr()
#curses.start_color()
#print "TERM is", curses.termname()
#if curses.has_colors():
# print "Has colors"#
#print curses.color_pair(curses.COLOR_RED), "Red"
#curses.endwin()
#curses.setupterm('xterm')
curses.setupterm()
if sys.stdout.isatty():
print "Is a TTY"
print "Size is %sx%s" % (curses.tigetnum('lines'), curses.tigetnum('cols'))
if curses.tigetnum('colors') > 0:
print "Has colors"
print curses.tigetnum('colors')
<file_sep>/rs-sysmon2/plugins/dstat_top_io_adv.py
### Dstat all I/O process plugin
### Displays all processes' I/O read/write stats and CPU usage
###
### Authority: <NAME>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'most expensive i/o process'
self.vars = ('process pid read write cpu',)
self.type = 's'
self.width = 40
self.scale = 0
self.pidset1 = {}
def check(self):
if not os.access('/proc/self/io', os.R_OK):
raise Exception, 'Kernel has no I/O accounting, use at least 2.6.20.'
return True
def extract(self):
self.output = ''
self.pidset2 = {}
self.val['usage'] = 0.0
for pid in proc_pidlist():
try:
### Reset values
if not self.pidset2.has_key(pid):
self.pidset2[pid] = {'rchar:': 0, 'wchar:': 0, 'cputime:': 0, 'cpuper:': 0}
if not self.pidset1.has_key(pid):
self.pidset1[pid] = {'rchar:': 0, 'wchar:': 0, 'cputime:': 0, 'cpuper:': 0}
### Extract name
name = proc_splitline('/proc/%s/stat' % pid)[1][1:-1]
### Extract counters
for l in proc_splitlines('/proc/%s/io' % pid):
if len(l) != 2: continue
self.pidset2[pid][l[0]] = int(l[1])
### Get CPU usage
l = proc_splitline('/proc/%s/stat' % pid)
if len(l) < 15:
cpu_usage = 0
else:
self.pidset2[pid]['cputime:'] = int(l[13]) + int(l[14])
cpu_usage = (self.pidset2[pid]['cputime:'] - self.pidset1[pid]['cputime:']) * 1.0 / elapsed / cpunr
except ValueError:
continue
except IOError:
continue
except IndexError:
continue
read_usage = (self.pidset2[pid]['rchar:'] - self.pidset1[pid]['rchar:']) * 1.0 / elapsed
write_usage = (self.pidset2[pid]['wchar:'] - self.pidset1[pid]['wchar:']) * 1.0 / elapsed
usage = read_usage + write_usage
### Get the process that spends the most jiffies
if usage > self.val['usage']:
self.val['usage'] = usage
self.val['read_usage'] = read_usage
self.val['write_usage'] = write_usage
self.val['pid'] = pid
self.val['name'] = getnamebypid(pid, name)
self.val['cpu_usage'] = cpu_usage
if step == op.delay:
self.pidset1 = self.pidset2
if self.val['usage'] != 0.0:
self.output = '%-*s%s%-5s%s%s%s%s%%' % (self.width-14-len(pid), self.val['name'][0:self.width-14-len(pid)], ansi['darkblue'], self.val['pid'], cprint(self.val['read_usage'], 'd', 5, 1024), cprint(self.val['write_usage'], 'd', 5, 1024), cprint(self.val['cpu_usage'], 'f', 3, 34), ansi['darkgray'])
def showcsv(self):
return self.val['i/o process'] + 'Top: %s\t%s\t%s\t%s' % (self.val['name'][0:self.width-20], self.val['read_usage'], self.val['write_usage'], self.val['cpu_usage'])
<file_sep>/rs-sysmon2/plugins/dstat_test.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
'''
Provides a test playground to test syntax and structure.
'''
def __init__(self):
self.name = 'test'
self.nick = ( 'f1', 'f2' )
self.vars = ( 'f1', 'f2' )
# self.type = 'd'
# self.width = 4
# self.scale = 20
self.type = 's'
self.width = 4
self.scale = 0
def extract(self):
# Self.val = { 'f1': -1, 'f2': -1 }
self.val = { 'f1': 'test', 'f2': 'test' }
# vim:ts=4:sw=4:et
<file_sep>/src/dbseer/middleware/packet/MiddlewarePacket.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.packet;
import java.io.UnsupportedEncodingException;
/**
* Created by <NAME> on 12/2/15.
*/
public class MiddlewarePacket
{
public int header;
public int length;
public String body;
public MiddlewarePacket(int header, int length, String body)
{
this.header = header;
this.length = length;
this.body = body;
}
public MiddlewarePacket(int header, String body)
{
this.header = header;
this.body = body;
try
{
this.length = body.getBytes("UTF-8").length;
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
public MiddlewarePacket(int header)
{
this.header = header;
this.length = 0;
}
}
<file_sep>/rs-sysmon2/plugins/dstat_vz_cpu.py
### Author: <NAME> <<EMAIL>>
#Version: 2.2
#VEID user nice system uptime idle strv uptime used maxlat totlat numsched
#302 142926 0 10252 152896388 852779112954062 0 427034187248480 1048603937010 0 0 0
#301 27188 0 7896 152899846 853267000490282 0 427043845492614 701812592320 0 0 0
class dstat_plugin(dstat):
def __init__(self):
self.nick = ('usr', 'sys', 'idl', 'nic')
self.type = 'p'
self.width = 3
self.scale = 34
self.open('/proc/vz/vestat')
self.cols = 4
def check(self):
info(1, 'Module %s is still experimental.' % self.filename)
def discover(self, *list):
ret = []
for l in self.splitlines():
if len(l) < 6 or l[0] == 'VEID': continue
ret.append(l[0])
ret.sort()
for item in list: ret.append(item)
return ret
def name(self):
ret = []
for name in self.vars:
if name == 'total':
ret.append('total ve usage')
else:
ret.append('ve ' + name + ' usage')
return ret
def vars(self):
ret = []
if not op.full:
list = ('total', )
else:
list = self.discover
for name in list:
if name in self.discover + ['total']:
ret.append(name)
return ret
def extract(self):
self.set2['total'] = [0, 0, 0, 0]
for line in self.splitlines():
if len(l) < 6 or l[0] == 'VEID': continue
name = l[0]
self.set2[name] = ( long(l[1]), long(l[3]), long(l[4]) - long(l[1]) - long(l[2]) - long(l[3]), long(l[2]) )
self.set2['total'] = ( self.set2['total'][0] + long(l[1]), self.set2['total'][1] + long(l[3]), self.set2['total'][2] + long(l[4]) - long(l[1]) - long(l[2]) - long(l[3]), self.set2['total'][3] + long(l[2]) )
for name in self.vars:
for i in range(4):
self.val[name][i] = 100.0 * (self.set2[name][i] - self.set1[name][i]) / (sum(self.set2[name]) - sum(self.set1[name]))
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/src/dbseer/middleware/client/MiddlewareClient.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.client;
import com.esotericsoftware.minlog.Log;
import dbseer.middleware.constant.MiddlewareConstants;
import dbseer.middleware.event.MiddlewareClientEvent;
import dbseer.middleware.packet.MiddlewarePacket;
import dbseer.middleware.packet.MiddlewarePacketDecoder;
import dbseer.middleware.packet.MiddlewarePacketEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.timeout.IdleStateHandler;
import java.io.*;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Created by <NAME> on 12/1/15.
*
* The client for the middleware.
*/
public class MiddlewareClient extends Observable implements Runnable
{
private static final int MAX_RETRY = 3;
private String id;
private String password;
private String host;
private int port;
private int retry;
private int reqId;
private boolean isMonitoring;
private String logPath;
private Channel channel = null;
private ExecutorService requesterExecutor = null;
private ExecutorService heartbeatSenderExecutor = null;
private MiddlewareClientHeartbeatSender heartbeatSender = null;
private MiddlewareClientLogRequester txLogRequester = null;
private Map<String, MiddlewareClientLogRequester> sysLogRequester = null;
private Map<String, PrintWriter> logWriterMap = null; // tx log writer for dbseer: <transaction type, writer>
private Map<Integer, String> statementMessageMap = null;
private ArrayList<String> serverNameList = null;
private ZipOutputStream txZipOutputStream = null;
private PrintWriter txPrintWriter = null;
private File txLogFileRaw = null;
public MiddlewareClient(String host, String id, String password, int port, String logPath)
{
this.retry = 0;
this.reqId = 0;
this.id = id;
this.password = <PASSWORD>;
this.host = host;
this.port = port;
this.logPath = logPath;
this.isMonitoring = false;
this.logWriterMap = new HashMap<>();
this.sysLogRequester = new HashMap<>();
this.statementMessageMap = new HashMap<>();
this.serverNameList = new ArrayList<>();
}
public void setLogLevel(int level)
{
Log.set(level);
}
public void run()
{
// debug info
Log.debug(String.format("host = %s", host));
Log.debug(String.format("port = %d", port));
Log.debug(String.format("log path = %s", logPath));
// client needs to handle incoming messages from the middleware as well.
EventLoopGroup group = new NioEventLoopGroup(4);
try
{
// attach shutdown hook.
MiddlewareClientShutdown shutdownThread = new MiddlewareClientShutdown(this);
Runtime.getRuntime().addShutdownHook(shutdownThread);
File logDir = new File(logPath);
if (!logDir.exists())
{
logDir.mkdirs();
}
final MiddlewareClient client = this;
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
.handler(new ChannelInitializer<SocketChannel>()
{
@Override
protected void initChannel(SocketChannel ch) throws Exception
{
ChannelPipeline p = ch.pipeline();
p.addLast(new IdleStateHandler(10, 0, 0));
p.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.ZLIB));
p.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.ZLIB));
p.addLast(new MiddlewarePacketDecoder());
p.addLast(new MiddlewarePacketEncoder());
p.addLast(new MiddlewareClientHandler(client));
}
});
ChannelFuture f = b.connect(host, port).sync();
channel = f.channel();
Log.debug("Connected to the middleware.");
MiddlewarePacket checkPacket = new MiddlewarePacket(MiddlewareConstants.PACKET_CHECK_VERSION, MiddlewareConstants.PROTOCOL_VERSION);
// ByteBuf buf = Unpooled.buffer();
// buf.writeInt(MiddlewareConstants.PACKET_CHECK_VERSION);
// buf.writeInt(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8").length);
// buf.writeBytes(MiddlewareConstants.PROTOCOL_VERSION.getBytes("UTF-8"));
// channel.writeAndFlush(buf);
channel.writeAndFlush(checkPacket);
channel.closeFuture().sync();
}
catch (Exception e)
{
if (e instanceof InterruptedException)
{
}
else
{
setChanged();
notifyObservers(new MiddlewareClientEvent(MiddlewareClientEvent.ERROR, e));
}
Log.error(e.getMessage());
e.printStackTrace();
}
finally
{
group.shutdownGracefully();
this.stopExecutors();
if (txLogFileRaw.exists())
{
txLogFileRaw.delete();
}
if (txZipOutputStream != null)
{
try
{
txZipOutputStream.closeEntry();
txZipOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
txZipOutputStream = null;
}
}
}
public Channel getChannel()
{
return channel;
}
public MiddlewareClientLogRequester getTxLogRequester()
{
return txLogRequester;
}
public MiddlewareClientLogRequester getSysLogRequester(String server)
{
return sysLogRequester.get(server);
}
public void startMonitoring() throws Exception
{
if (retry >= MAX_RETRY)
{
throw new Exception(String.format("Middleware failed to start with %d retries", MAX_RETRY));
}
// clear server names.
this.serverNameList.clear();
if (channel != null)
{
String idPassword = <PASSWORD> + "@" + this.<PASSWORD>;
// ByteBuf b = Unpooled.buffer();
// b.writeInt(MiddlewareConstants.PACKET_START_MONITORING);
// b.writeInt(idPassword.getBytes("UTF-8").length);
// b.writeBytes(idPassword.getBytes("UTF-8"));
// channel.writeAndFlush(b);
MiddlewarePacket packet = new MiddlewarePacket(MiddlewareConstants.PACKET_START_MONITORING, idPassword);
channel.writeAndFlush(packet);
}
Log.debug("Start monitoring packet sent.");
retry++;
}
public void stopMonitoring() throws Exception
{
this.stopExecutors();
if (channel != null)
{
// ByteBuf b = Unpooled.buffer();
// b.writeInt(MiddlewareConstants.PACKET_STOP_MONITORING);
// b.writeInt(0);
// channel.writeAndFlush(b);
MiddlewarePacket packet = new MiddlewarePacket(MiddlewareConstants.PACKET_STOP_MONITORING);
channel.writeAndFlush(packet);
}
Log.debug("Stop monitoring packet sent.");
if (txLogFileRaw != null && txLogFileRaw.exists())
{
txLogFileRaw.delete();
}
if (txZipOutputStream != null)
{
txZipOutputStream.closeEntry();
txZipOutputStream.close();
txZipOutputStream = null;
}
// reset retry count.
retry = 0;
isMonitoring = false;
}
public File getTxLogFileRaw()
{
return txLogFileRaw;
}
public void requestServerList() throws Exception
{
if (channel != null)
{
// ByteBuf b= Unpooled.buffer();
// b.writeInt(MiddlewareConstants.PACKET_REQUEST_SERVER_LIST);
// b.writeInt(0);
// channel.writeAndFlush(b);
MiddlewarePacket packet = new MiddlewarePacket(MiddlewareConstants.PACKET_REQUEST_SERVER_LIST);
channel.writeAndFlush(packet);
}
Log.debug("Server list request packet sent.");
}
public synchronized void requestStatistics(String serverName, int txId, int txType, int stId, long latency, int mode, Set<String> tables, String sql)
{
String msg = String.format("%d,%d,%d,%d,%d,%d,", txType, txId, stId, latency, mode, tables.size());
for (String table : tables)
{
msg += table + ",";
}
statementMessageMap.put(reqId, msg);
if (channel != null)
{
MiddlewarePacket packet = new MiddlewarePacket(MiddlewareConstants.PACKET_REQUEST_QUERY_STATISTICS, String.format("%s,%d,%d,%s", serverName, reqId, txType, sql));
channel.writeAndFlush(packet);
}
++reqId;
Log.debug("Table count request packet sent.");
}
public void requestTableCount(String serverName, String tableName)
{
if (channel != null)
{
MiddlewarePacket packet = new MiddlewarePacket(MiddlewareConstants.PACKET_REQUEST_TABLE_COUNT, String.format("%s,%s", serverName, tableName));
channel.writeAndFlush(packet);
}
Log.debug("Table count request packet sent.");
}
public void requestNumRowAccessedByQuery(String serverName, int txType, String sql)
{
if (channel != null)
{
MiddlewarePacket packet = new MiddlewarePacket(MiddlewareConstants.PACKET_REQUEST_NUM_ROW_BY_SQL, String.format("%s,%d,%s", serverName, txType, sql));
channel.writeAndFlush(packet);
}
Log.debug("Num row accessed by sql request packet sent.");
}
public synchronized void printQueryStatistics(String serverName, int txType, int reqId, String msg)
{
PrintWriter writer = logWriterMap.get(serverName + txType);
if (writer != null)
{
writer.print(statementMessageMap.get(reqId));
writer.println(msg);
writer.flush();
}
else
{
Log.error("Writer null");
}
statementMessageMap.remove(reqId);
}
public ZipOutputStream startTxLogRequester() throws Exception
{
if (requesterExecutor == null)
{
requesterExecutor = Executors.newCachedThreadPool();
}
txLogRequester =
new MiddlewareClientLogRequester(channel, MiddlewareConstants.PACKET_REQUEST_TX_LOG);
requesterExecutor.submit(txLogRequester);
File dbLogFile = new File(logPath + File.separator + MiddlewareConstants.TX_LOG_ZIP);
txLogFileRaw = new File(logPath + File.separator + MiddlewareConstants.TX_LOG_RAW);
txPrintWriter = new PrintWriter(new FileWriter(txLogFileRaw, false));
FileOutputStream fos = new FileOutputStream(dbLogFile);
txZipOutputStream = new ZipOutputStream(new BufferedOutputStream(fos));
try
{
txZipOutputStream.putNextEntry(new ZipEntry(MiddlewareConstants.TX_LOG_RAW));
}
catch (Exception e)
{
Log.error(e.getMessage());
e.printStackTrace();
}
Log.debug("Tx Log requester launched.");
return txZipOutputStream;
}
public PrintWriter getTxPrintWriter()
{
return txPrintWriter;
}
public Map<String, PrintWriter> startSysLogRequester(String serverStr) throws Exception
{
if (requesterExecutor == null)
{
requesterExecutor = Executors.newCachedThreadPool();
}
Map<String, PrintWriter> writers = new HashMap<>();
String[] servers = serverStr.split(MiddlewareConstants.SERVER_STRING_DELIMITER);
for (String server : servers)
{
MiddlewareClientLogRequester logRequester =
new MiddlewareClientLogRequester(channel, MiddlewareConstants.PACKET_REQUEST_SYS_LOG, server);
requesterExecutor.submit(logRequester);
sysLogRequester.put(server, logRequester);
File sysLogFile = new File(logPath + File.separator + MiddlewareConstants.SYS_LOG_PREFIX + "." + server);
PrintWriter writer = new PrintWriter(new FileWriter(sysLogFile, false));
writers.put(server, writer);
serverNameList.add(server);
}
Log.debug("Sys Log requesters launched.");
return writers;
}
public void startHeartbeatSender() throws Exception
{
heartbeatSender = new MiddlewareClientHeartbeatSender(channel);
heartbeatSenderExecutor = Executors.newSingleThreadExecutor();
heartbeatSenderExecutor.submit(heartbeatSender);
Log.debug("heartbeat sender launched.");
}
public void stopExecutors()
{
if (requesterExecutor != null)
{
requesterExecutor.shutdownNow();
}
if (heartbeatSenderExecutor != null)
{
heartbeatSenderExecutor.shutdownNow();
}
txLogRequester = null;
sysLogRequester = new HashMap<>();
// clear server names.
this.serverNameList.clear();
}
public ZipOutputStream getTxZipOutputStream()
{
return txZipOutputStream;
}
public void setMonitoring(boolean monitoring)
{
isMonitoring = monitoring;
setChanged();
MiddlewareClientEvent event;
if (isMonitoring)
{
event = new MiddlewareClientEvent(MiddlewareClientEvent.IS_MONITORING);
}
else
{
event = new MiddlewareClientEvent(MiddlewareClientEvent.IS_NOT_MONITORING);
}
notifyObservers(event);
}
public void setMonitoring(boolean monitoring, String serverStr)
{
isMonitoring = monitoring;
setChanged();
MiddlewareClientEvent event;
if (isMonitoring)
{
event = new MiddlewareClientEvent(MiddlewareClientEvent.IS_MONITORING);
}
else
{
event = new MiddlewareClientEvent(MiddlewareClientEvent.IS_NOT_MONITORING);
}
event.serverStr = serverStr;
notifyObservers(event);
}
public void setTableRowCount(String serverName, String tableName, long rowCount)
{
MiddlewareClientEvent event = new MiddlewareClientEvent(MiddlewareClientEvent.TABLE_ROW_COUNT, serverName, tableName, rowCount);
setChanged();
notifyObservers(event);
}
public boolean isMonitoring()
{
return isMonitoring;
}
public void registerLogWriter(String id, PrintWriter writer)
{
logWriterMap.put(id, writer);
}
public void disconnect() throws Exception
{
if (channel != null && channel.isActive())
{
channel.disconnect();
}
}
public ArrayList<String> getServerNameList()
{
return serverNameList;
}
}
<file_sep>/src/dbseer/middleware/event/MiddlewareClientEvent.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.event;
import java.util.List;
/**
* Created by <NAME> on 1/3/16.
*/
public class MiddlewareClientEvent
{
public static final int IS_MONITORING = 1;
public static final int IS_NOT_MONITORING = 2;
public static final int ERROR = 3;
public static final int TABLE_ROW_COUNT = 4;
public int event;
public long count;
public Exception e;
public String error;
public String serverStr;
public String serverName;
public String tableName;
public MiddlewareClientEvent(int event)
{
this.event = event;
}
public MiddlewareClientEvent(int event, Exception e)
{
this.event = event;
this.e = e;
}
public MiddlewareClientEvent(int event, String serverName, String tableName, long count)
{
this.event = event;
this.serverName = serverName;
this.tableName = tableName;
this.count = count;
}
public MiddlewareClientEvent(int event, String error)
{
this.event = event;
this.error = error;
}
}
<file_sep>/middleware.sh
#!/bin/bash
BIN_PATH=bin:lib/*
java -cp "$BIN_PATH" dbseer.middleware.server.MiddlewareServer $@
<file_sep>/rs-sysmon2/plugins/dstat_qmail.py
### Author: <NAME> <tom$ctors,net>
class dstat_plugin(dstat):
"""
port of qmail_qstat to dstat
"""
def __init__(self):
self.name = 'qmail'
self.nick = ('in_queue', 'not_prep')
self.vars = ('mess', 'todo')
self.type = 'd'
self.width = 4
self.scale = 100
def check(self):
for item in self.vars:
if not os.access('/var/qmail/queue/'+item, os.R_OK):
raise Exception, 'Cannot access qmail queues'
def extract(self):
for item in self.vars:
self.val[item] = len(glob.glob('/var/qmail/queue/'+item+'/*/*'))
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_power.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Power usage information from ACPI.
Displays the power usage in watt per hour of your system's battery using
ACPI information. This information is only available when the battery is
being used (or being charged).
"""
def __init__(self):
self.name = 'power'
self.nick = ( 'usage', )
self.vars = ( 'rate', )
self.type = 'f'
self.width = 5
self.scale = 1
self.rate = 0
self.batteries = []
for battery in os.listdir('/proc/acpi/battery/'):
for line in dopen('/proc/acpi/battery/'+battery+'/state').readlines():
l = line.split()
if len(l) < 2: continue
self.batteries.append(battery)
break
def check(self):
if not self.batteries:
raise Exception, 'No battery information found, no power usage statistics'
def extract(self):
amperes_drawn = 0
voltage = 0
watts_drawn = 0
for battery in self.batteries:
for line in dopen('/proc/acpi/battery/'+battery+'/state').readlines():
l = line.split()
if len(l) < 3: continue
if l[0] == 'present:' and l[1] != 'yes': continue
if l[0:2] == ['charging','state:'] and l[2] != 'discharging':
voltage = 0
break
if l[0:2] == ['present','voltage:']:
voltage = int(l[2]) / 1000.0
elif l[0:2] == ['present','rate:'] and l[3] == 'mW':
watts_drawn = int(l[2]) / 1000.0
elif l[0:2] == ['present','rate:'] and l[3] == 'mA':
amperes_drawn = int(l[2]) / 1000.0
self.rate = self.rate + watts_drawn + voltage * amperes_drawn
### Return error if we found no information
if self.rate == 0:
self.rate = -1
if op.update:
self.val['rate'] = self.rate / elapsed
else:
self.val['rate'] = self.rate
if step == op.delay:
self.rate = 0
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_disk_tps.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Number of read and write transactions per device.
Displays the number of read and write I/O transactions per device.
"""
def __init__(self):
self.nick = ('reads', 'writs' )
self.type = 'd'
self.scale = 1000
self.diskfilter = re.compile('^(dm-\d+|md\d+|[hsv]d[a-z]+\d+)$')
self.open('/proc/diskstats')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines():
if len(l) < 13: continue
if l[3:] == ['0',] * 11: continue
name = l[2]
ret.append(name)
for item in objlist: ret.append(item)
if not ret:
raise Exception, "No suitable block devices found to monitor"
return ret
def vars(self):
ret = []
if op.disklist:
varlist = op.disklist
elif not op.full:
varlist = ('total',)
else:
varlist = []
for name in self.discover:
if self.diskfilter.match(name): continue
if name not in blockdevices(): continue
varlist.append(name)
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total'] + op.diskset.keys():
ret.append(name)
return ret
def name(self):
return ['dsk/'+sysfs_dev(name) for name in self.vars]
def extract(self):
for name in self.vars: self.set2[name] = (0, 0)
for l in self.splitlines():
if len(l) < 13: continue
if l[3] == '0' and l[7] == '0': continue
name = l[2]
if l[3:] == ['0',] * 11: continue
if not self.diskfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[3]), self.set2['total'][1] + long(l[7]) )
if name in self.vars and name != 'total':
self.set2[name] = ( self.set2[name][0] + long(l[3]), self.set2[name][1] + long(l[7]))
for diskset in self.vars:
if diskset in op.diskset.keys():
for disk in op.diskset[diskset]:
if re.match('^'+disk+'$', name):
self.set2[diskset] = ( self.set2[diskset][0] + long(l[3]), self.set2[diskset][1] + long(l[7]) )
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) / elapsed,
(self.set2[name][1] - self.set1[name][1]) / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
# S_VALUE(ioj->rd_ios, ioi->rd_ios, itv),
# S_VALUE(ioj->wr_ios, ioi->wr_ios, itv),
<file_sep>/rs-sysmon2/plugins/dstat_net_packets.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Number of packets received and send per interface.
"""
def __init__(self):
self.nick = ('#recv', '#send')
self.type = 'f'
self.width = 5
self.scale = 1000
self.totalfilter = re.compile('^(lo|bond\d+|face|.+\.\d+)$')
self.open('/proc/net/dev')
self.cols = 2
def discover(self, *objlist):
ret = []
for l in self.splitlines(replace=':'):
if len(l) < 17: continue
if l[2] == '0' and l[10] == '0': continue
name = l[0]
if name not in ('lo', 'face'):
ret.append(name)
ret.sort()
for item in objlist: ret.append(item)
return ret
def vars(self):
ret = []
if op.netlist:
varlist = op.netlist
elif not op.full:
varlist = ('total',)
else:
varlist = self.discover
# if len(varlist) > 2: varlist = varlist[0:2]
varlist.sort()
for name in varlist:
if name in self.discover + ['total', 'lo']:
ret.append(name)
if not ret:
raise Exception, "No suitable network interfaces found to monitor"
return ret
def name(self):
return ['pkt/'+name for name in self.vars]
def extract(self):
self.set2['total'] = [0, 0]
for l in self.splitlines(replace=':'):
if len(l) < 17: continue
if l[2] == '0' and l[10] == '0': continue
name = l[0]
if name in self.vars :
self.set2[name] = ( long(l[2]), long(l[10]) )
if not self.totalfilter.match(name):
self.set2['total'] = ( self.set2['total'][0] + long(l[2]), self.set2['total'][1] + long(l[10]))
if update:
for name in self.set2.keys():
self.val[name] = (
(self.set2[name][0] - self.set1[name][0]) * 1.0 / elapsed,
(self.set2[name][1] - self.set1[name][1]) * 1.0 / elapsed,
)
if step == op.delay:
self.set1.update(self.set2)
<file_sep>/rs-sysmon2/Makefile
name = dstat
version = $(shell awk '/^Version: / {print $$2}' $(name).spec)
prefix = /usr
sysconfdir = /etc
bindir = $(prefix)/bin
datadir = $(prefix)/share
mandir = $(datadir)/man
.PHONY: all install docs clean
all: docs
@echo "Nothing to be build."
docs:
$(MAKE) -C docs docs
install:
# -[ ! -f $(DESTDIR)$(sysconfdir)/dstat.conf ] && install -D -m0644 dstat.conf $(DESTDIR)$(sysconfdir)/dstat.conf
install -Dp -m0755 dstat $(DESTDIR)$(bindir)/dstat
install -d -m0755 $(DESTDIR)$(datadir)/dstat/
install -Dp -m0755 dstat $(DESTDIR)$(datadir)/dstat/dstat.py
install -Dp -m0644 plugins/dstat_*.py $(DESTDIR)$(datadir)/dstat/
# install -d -m0755 $(DESTDIR)$(datadir)/dstat/examples/
# install -Dp -m0755 examples/*.py $(DESTDIR)$(datadir)/dstat/examples/
install -Dp -m0644 docs/dstat.1 $(DESTDIR)$(mandir)/man1/dstat.1
docs-install:
$(MAKE) -C docs install
clean:
rm -f examples/*.pyc plugins/*.pyc
$(MAKE) -C docs clean
dist: clean
$(MAKE) -C docs dist
svn up
svn list -R | pax -d -w -x ustar -s ,^,$(name)-$(version)/, | bzip2 >../$(name)-$(version).tar.bz2
rpm: dist
rpmbuild -tb --clean --rmspec --define "_rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm" --define "_rpmdir ../" ../$(name)-$(version).tar.bz2
srpm: dist
rpmbuild -ts --clean --rmspec --define "_rpmfilename %%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm" --define "_srcrpmdir ../" ../$(name)-$(version).tar.bz2
<file_sep>/rs-sysmon2/plugins/dstat_dstat_ctxt.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Provide Dstat's number of voluntary and involuntary context switches.
This plugin provides a unique view of the number of voluntary and
involuntary context switches of the Dstat process itself. It may help
to vizualise the performance of Dstat and its selection of plugins.
"""
def __init__(self):
self.name = 'contxt sw'
self.vars = ('voluntary', 'involuntary', 'total')
self.type = 'd'
self.width = 3
self.scale = 100
def extract(self):
res = resource.getrusage(resource.RUSAGE_SELF)
self.set2['voluntary'] = float(res.ru_nvcsw)
self.set2['involuntary'] = float(res.ru_nivcsw)
self.set2['total'] = (float(res.ru_nvcsw) + float(res.ru_nivcsw))
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_dbus.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Number of active dbus sessions.
"""
def __init__(self):
self.name = 'dbus'
self.nick = ('sys', 'ses')
self.vars = ('system', 'session')
self.type = 'd'
self.width = 3
self.scale = 100
def check(self):
# dstat.info(1, 'The dbus module is an EXPERIMENTAL module.')
try:
global dbus
import dbus
try:
self.sysbus = dbus.Bus(dbus.Bus.TYPE_SYSTEM).get_service('org.freedesktop.DBus').get_object('/org/freedesktop/DBus', 'org.freedesktop.DBus')
try:
self.sesbus = dbus.Bus(dbus.Bus.TYPE_SESSION).get_service('org.freedesktop.DBus').get_object('/org/freedesktop/DBus', 'org.freedesktop.DBus')
except:
self.sesbus = None
except:
raise Exception, 'Unable to connect to dbus message bus'
except:
raise Exception, 'Needs python-dbus module'
def extract(self):
self.val['system'] = len(self.sysbus.ListServices()) - 1
try:
self.val['session'] = len(self.sesbus.ListServices()) - 1
except:
self.val['session'] = -1
# print dir(b); print dir(s); print dir(d); print d.ListServices()
# print dir(d)
# print d.ListServices()
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_rpcd.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'rpc server'
self.nick = ('call', 'erca', 'erau', 'ercl', 'xdrc')
self.vars = ('calls', 'badcalls', 'badauth', 'badclnt', 'xdrcall')
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/net/rpc/nfsd')
def extract(self):
for l in self.splitlines():
if not l or l[0] != 'rpc': continue
for i, name in enumerate(self.vars):
self.set2[name] = long(l[i+1])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_vz_ubc.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.nick = ('fcnt', )
self.type = 'd'
self.width = 5
self.scale = 1000
self.open('/proc/user_beancounters')
self.cols = 1 ### Is this correct ?
def check(self):
info(1, 'Module %s is still experimental.' % self.filename)
def discover(self, *list):
ret = []
for l in self.splitlines():
if len(l) < 7 or l[0] in ('uid', '0:'): continue
ret.append(l[0][0:-1])
ret.sort()
for item in list: ret.append(item)
return ret
def name(self):
ret = []
for name in self.vars:
if name == 'total':
ret.append('total failcnt')
else:
ret.append(name)
return ret
def vars(self):
ret = []
if not op.full:
list = ('total', )
else:
list = self.discover
for name in list:
if name in self.discover + ['total']:
ret.append(name)
return ret
def extract(self):
for name in self.vars + ['total']:
self.set2[name] = 0
for l in self.splitlines():
if len(l) < 6 or l[0] == 'uid':
continue
elif len(l) == 7:
name = l[0][0:-1]
if name in self.vars:
self.set2[name] = self.set2[name] + long(l[6])
self.set2['total'] = self.set2['total'] + long(l[6])
elif name == '0':
continue
else:
if name in self.vars:
self.set2[name] = self.set2[name] + long(l[5])
self.set2['total'] = self.set2['total'] + long(l[5])
for name in self.vars:
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4:et
<file_sep>/rs-sysmon2/plugins/dstat_memcache_hits.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
"""
Memcache hit count plugin.
Displays the number of memcache get_hits and get_misses.
"""
def __init__(self):
self.name = 'Memcache Hits'
self.nick = ('Hit', 'Miss')
self.vars = ('get_hits', 'get_misses')
self.type = 'd'
self.width = 6
self.scale = 50
def check(self):
try:
global memcache
import memcache
self.mc = memcache.Client(['127.0.0.1:11211'], debug=0)
except:
raise Exception, 'Plugin needs the memcache module'
def extract(self):
stats = self.mc.get_stats()
for key in self.vars:
self.val[key] = long(stats[0][1][key])
<file_sep>/src/dbseer/middleware/test/MiddlewareClientTest.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.test;
import com.esotericsoftware.minlog.Log;
import dbseer.middleware.client.MiddlewareClient;
import org.apache.commons.cli.*;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Created by <NAME> on 12/1/15.
*
* The test class for testing the middleware client.
*/
public class MiddlewareClientTest
{
public static void main(String[] args)
{
ExecutorService clientExecutor = Executors.newSingleThreadExecutor();
// set up logger
Log.set(Log.LEVEL_DEBUG);
// handle command-line options
CommandLineParser clParser = new DefaultParser();
Options options = new Options();
Option idOption = Option.builder("i")
.hasArg()
.argName("ID")
.required(true)
.desc("middleware user id")
.build();
Option passwordOption = Option.builder("w")
.hasArg()
.argName("PASSWORD")
.required(true)
.desc("middleware user password")
.build();
Option hostOption = Option.builder("h")
.hasArg()
.argName("HOST")
.required(true)
.desc("middleware hostname")
.build();
Option portOption = Option.builder("p")
.hasArg()
.argName("PORT")
.required(true)
.desc("middleware port")
.build();
Option logOption = Option.builder("d")
.hasArg()
.argName("FILE")
.required(true)
.desc("path to print logs")
.build();
Option helpOption = Option.builder("?")
.longOpt("help")
.required(false)
.desc("print this message")
.build();
options.addOption(idOption);
options.addOption(passwordOption);
options.addOption(hostOption);
options.addOption(portOption);
options.addOption(logOption);
options.addOption(helpOption);
HelpFormatter formatter = new HelpFormatter();
try
{
CommandLine line = clParser.parse(options, args);
if (line.hasOption("?"))
{
formatter.printHelp("MiddlewareClientTest", options, true);
return;
}
int port;
String host, logPath, id, password;
id = line.getOptionValue("i");
password = line.getOptionValue("w");
port = Integer.parseInt(line.getOptionValue("p"));
host = line.getOptionValue("h");
logPath = line.getOptionValue("d");
MiddlewareClient client = new MiddlewareClient(host, id, password, port, logPath);
client.setLogLevel(Log.LEVEL_DEBUG);
Future clientFuture = clientExecutor.submit(client);
Thread.sleep(1000);
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext())
{
String input = scanner.nextLine();
if (input.equalsIgnoreCase("s"))
{
client.startMonitoring();
}
else if (input.equalsIgnoreCase("t"))
{
client.stopMonitoring();
}
else if (input.equalsIgnoreCase("q"))
{
clientExecutor.shutdownNow();
break;
}
}
clientFuture.get();
}
catch (ParseException e)
{
formatter.printHelp("MiddlewareClientTest", options, true);
Log.error(e.getMessage());
}
catch (Exception e)
{
Log.error(e.getMessage());
e.printStackTrace();
}
}
}
<file_sep>/rs-sysmon2/monitor.sh
echo "------------------- MONITORING TOOl --------------"
#. ./setenv
echo $$ > ./monitor.pid
rm $DSTAT_OUTPUT_PATH 2> /dev/null
exec ./dstat --noupdate -T -l -f -c -m -n -d -r --aio -s -g --vm --fs -i -y -p --disk-util --top-mysql-cpu --mysql5-all1 --mysql5-log-size --mysql-ndb --client-events --output $DSTAT_OUTPUT_PATH
#if [ ""$DSTAT_CONFIGURED != "true" ]
#then
#echo "I believe you haven't configured the environment variables in the \"setenv\" script yet... please do so and relaunch monitor.sh"
#else
#echo "I'm recording in "$DSTAT_HOMEDIR"/log_exp_"$DSTAT_EXPERIMENT_ID".csv the system load every "$DSTAT_MONITORING_FREQUENCY" seconds... Generate your load..."
#if [ ""$DSTAT_MONITOR_MYSQL == "true" ]
#then
#echo "monitoring mysql"
#$DSTAT_HOMEDIR/dstat --noupdate -T -l -f -c -m -n -d -r --aio -s -g --vm --fs -i -y -p --disk-util --top-mysql-cpu --mysql5-all1 --mysql-ndb --client-events --output $DSTAT_HOMEDIR"/../Transactions/log_exp_"$DSTAT_EXPERIMENT_ID".csv" $DSTAT_MONITORING_FREQUENCY
#elif [ ""$DSTAT_MONITOR_POSTGRES == "true" ]
#then
#echo "monitoring postgres"
#$DSTAT_HOMEDIR/dstat --noupdate -T -l -f -c -m -n -d -r --aio -s -g --vm --fs -i -y -p --disk-util --postgres-all1 --postgres-cpu-bio --output $DSTAT_HOMEDIR"/log_exp_"$DSTAT_EXPERIMENT_ID".csv" $DSTAT_MONITORING_FREQUENCY
#else
#echo "monitoring neither mysql nor postgres"
#$DSTAT_HOMEDIR/dstat --noupdate -T -l -f -c -m -n -d -r --aio -s -g --vm --fs -i -y -p --disk-util --client-events --output $DSTAT_HOMEDIR"/log_exp_"$DSTAT_EXPERIMENT_ID".csv" $DSTAT_MONITORING_FREQUENCY
#fi > /dev/null
#fi
#echo "----------------------------------------------------"
<file_sep>/rs-sysmon2/plugins/dstat_vmk_int.py
### Author: <NAME> <bert+dstat$debruijn,be>
### VMware ESX kernel interrupt stats
### Displays kernel interrupt statistics on VMware ESX servers
# NOTE TO USERS: command-line plugin configuration is not yet possible, so I've
# "borrowed" the -I argument.
# EXAMPLES:
# # dstat --vmkint -I 0x46,0x5a
# You can even combine the Linux and VMkernel interrupt stats
# # dstat --vmkint -i -I 14,0x5a
# Look at /proc/vmware/interrupts to see which interrupt is linked to which function
class dstat_plugin(dstat):
def __init__(self):
self.name = 'vmkint'
self.type = 'd'
self.width = 4
self.scale = 1000
self.open('/proc/vmware/interrupts')
# self.intmap = self.intmap()
# def intmap(self):
# ret = {}
# for line in dopen('/proc/vmware/interrupts').readlines():
# l = line.split()
# if len(l) <= self.vmkcpunr: continue
# l1 = l[0].split(':')[0]
# l2 = ' '.join(l[vmkcpunr()+1:]).split(',')
# ret[l1] = l1
# for name in l2:
# ret[name.strip().lower()] = l1
# return ret
def vmkcpunr(self):
#the service console sees only one CPU, so cpunr == 1, only the vmkernel sees all CPUs
ret = []
# default cpu number is 2
ret = 2
for l in self.fd[0].splitlines():
if l[0] == 'Vector':
ret = int( int( l[-1] ) + 1 )
return ret
def discover(self):
#interrupt names are not decimal numbers, but rather hexadecimal numbers like 0x7e
ret = []
self.fd[0].seek(0)
for line in self.fd[0].readlines():
l = line.split()
if l[0] == 'Vector': continue
if len(l) < self.vmkcpunr()+1: continue
name = l[0].split(':')[0]
amount = 0
for i in l[1:1+self.vmkcpunr()]:
amount = amount + long(i)
if amount > 20: ret.append(str(name))
return ret
def vars(self):
ret = []
if op.intlist:
list = op.intlist
else:
list = self.discover
# len(list) > 5: list = list[-5:]
for name in list:
if name in self.discover:
ret.append(name)
# elif name.lower() in self.intmap.keys():
# ret.append(self.intmap[name.lower()])
return ret
def check(self):
try:
os.listdir('/proc/vmware')
except:
raise Exception, 'Needs VMware ESX'
info(1, 'The vmkint module is an EXPERIMENTAL module.')
def extract(self):
self.fd[0].seek(0)
for line in self.fd[0].readlines():
l = line.split()
if len(l) < self.vmkcpunr()+1: continue
name = l[0].split(':')[0]
if name in self.vars:
self.set2[name] = 0
for i in l[1:1+self.vmkcpunr()]:
self.set2[name] = self.set2[name] + long(i)
for name in self.set2.keys():
self.val[name] = (self.set2[name] - self.set1[name]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
# vim:ts=4:sw=4
<file_sep>/rs-sysmon2/docs/Makefile
prefix = /usr
datadir = $(prefix)/share
mandir = $(datadir)/man
txttargets = $(shell echo *.txt)
htmltargets = $(patsubst %.txt, %.html, $(txttargets))
all:
dist: docs
docs: dstat.1 $(htmltargets)
install: dstat.1
install -Dp -m0644 dstat.1 $(DESTDIR)$(mandir)/man1/dstat.1
clean:
rm -f dstat.1 *.html *.xml
%.1.html: %.1.txt
asciidoc -d manpage $<
%.html: %.txt
asciidoc $<
%.1.xml: %.1.txt
asciidoc -b docbook -d manpage $<
%.1: %.1.xml
@xmlto man $<
<file_sep>/rs-sysmon2/plugins/dstat_postfix.py
### Author: <NAME> <<EMAIL>>
class dstat_plugin(dstat):
def __init__(self):
self.name = 'postfix'
self.nick = ('inco', 'actv', 'dfrd', 'bnce', 'defr')
self.vars = ('incoming', 'active', 'deferred', 'bounce', 'defer')
self.type = 'd'
self.width = 4
self.scale = 100
def check(self):
if not os.access('/var/spool/postfix/active', os.R_OK):
raise Exception, 'Cannot access postfix queues'
def extract(self):
for item in self.vars:
self.val[item] = len(glob.glob('/var/spool/postfix/'+item+'/*/*'))
# vim:ts=4:sw=4:et
<file_sep>/src/dbseer/middleware/data/Server.java
/*
* Copyright 2013 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dbseer.middleware.data;
import com.esotericsoftware.minlog.Log;
import dbseer.middleware.constant.MiddlewareConstants;
import dbseer.middleware.log.LogTailer;
import dbseer.middleware.log.LogTailerListener;
import java.io.File;
import java.util.*;
import java.sql.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created by <NAME> on 1/10/16.
*
* Server that the middleware monitors (different from MiddlewareServer itself)
*/
public class Server
{
String name;
String dbHost;
String dbPort;
String dbName;
String dbUser;
String dbPassword;
String sshUser;
String monitorDir;
String monitorScript;
String logPath;
String url;
Process monitorProcess;
File logFile;
Connection conn;
// private ArrayBlockingQueue<String> logQueue;
private LinkedBlockingQueue<String> logQueue;
private LogTailerListener logTailerListener;
private LogTailer logTailer;
private ExecutorService tailerExecutor;
List<String> tableList;
Map<String, Long> tableCount;
public Server(String name, String dbHost, String dbPort, String dbName, String dbUser, String dbPassword, String sshUser, String monitorDir, String monitorScript, String logPath)
{
this.name = name;
this.dbHost = dbHost;
this.dbPort = dbPort;
this.dbUser = dbUser;
this.dbName = dbName;
this.dbPassword = <PASSWORD>;
this.sshUser = sshUser;
this.monitorDir = monitorDir;
this.monitorScript = monitorScript;
this.logPath = logPath;
// this.logQueue = new ArrayBlockingQueue<>(MiddlewareConstants.QUEUE_SIZE);
this.url = String.format("jdbc:mysql://%s:%s/%s", dbHost, dbPort, dbName);
this.logQueue = new LinkedBlockingQueue<>();
this.tableList = new ArrayList<>();
this.tableCount = new HashMap<>();
}
public void printLogInfo()
{
Log.info(String.format("[Server : %s]", name));
Log.info(String.format("DB Host = %s", dbHost));
Log.info(String.format("DB Port = %s", dbPort));
Log.info(String.format("DB Name = %s", dbName));
Log.info(String.format("DB User = %s", dbUser));
Log.info(String.format("DB PW = %s", dbPassword));
Log.info(String.format("SSH User = %s", sshUser));
Log.info(String.format("Remote Monitor Dir = %s", monitorDir));
Log.info(String.format("Remote Monitor Script = %s", monitorScript));
}
public boolean testConnection()
{
boolean canConnect = false;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = (Connection) DriverManager.getConnection(url, dbUser, dbPassword);
// connection was successful.
canConnect = true;
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (SQLException e)
{
Log.debug("Caught a SQLException while testing connection to the server.");
}
if (canConnect)
{
Log.info(String.format("Getting DB statistics from database '%s' @ '%s'... This may take a few minutes.", dbName, name));
if (this.getTableList())
{
for (String table : tableList)
{
this.getTableCount(table);
}
} else
{
Log.error(String.format("Cannot obtain the list of tables from database '%s'", dbName));
return false;
}
}
return canConnect;
}
private boolean getTableList()
{
tableList.clear();
try
{
if (conn == null || conn.isClosed())
{
if (!this.testConnection())
{
// cannot connect... return -1
Log.error("No DB Connection.");
return false;
}
}
String query = String.format("SHOW TABLE STATUS IN %s;", dbName);
PreparedStatement stmt = conn.prepareStatement(query);
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
String tableName = rs.getString("Name");
Long rowCount = rs.getLong("Rows");
tableList.add(tableName);
tableCount.put(tableName.toLowerCase(), rowCount.longValue());
}
}
catch (SQLException e)
{
Log.debug("Caught a SQLException while getting table names for the database " + dbName);
return false;
}
return true;
}
public long getTableCount(String tableName)
{
Long count = tableCount.get(tableName.toLowerCase());
if (count == null)
{
return getTableCountFromDatabase(tableName);
}
else return count.longValue();
}
public long getTableCountFromDatabase(String tableName)
{
long count = -1;
try
{
if (conn == null || conn.isClosed())
{
if (!this.testConnection())
{
// cannot connect... return -1
Log.error("No DB Connection.");
return count;
}
}
String query = String.format("SELECT COUNT(*) as ROW_COUNT from %s;", tableName);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next())
{
count = rs.getInt(1);
}
else
{
Log.error("No result set");
}
}
catch (SQLException e)
{
Log.debug("Caught a SQLException while getting row counts for the table " + tableName);
}
if (count != -1)
{
tableCount.put(tableName.toLowerCase(), count);
}
return count;
}
public List<Integer> getNumRowAccessedByQuery(String sql)
{
ArrayList<Integer> results = new ArrayList<>();
int count = 0;
try
{
if (conn == null || conn.isClosed())
{
if (!this.testConnection())
{
// cannot connect... return -1
Log.error("No DB Connection.");
return null;
}
}
String query = String.format("EXPLAIN %s;", sql);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
results.add(rs.getInt("rows"));
// count += rs.getInt("rows");
}
}
catch (SQLException e)
{
Log.debug("Caught a SQLException while getting the number of rows accessed for the query: " + sql);
}
return results;
}
public boolean testMonitoringDir()
{
try
{
String sshCmd = "ssh";
String sshConnection = String.format("%s@%s", sshUser, dbHost);
String sshEndCmd = String.format("cd %s && ls -l ./%s 1> /dev/null", monitorDir, monitorScript);
String[] cmds = {sshCmd, sshConnection, sshEndCmd};
ProcessBuilder pb = new ProcessBuilder(cmds);
monitorProcess = pb.start();
int retVal = monitorProcess.waitFor();
if (retVal != 0)
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
public void startMonitoring() throws Exception
{
if (monitorProcess != null)
{
monitorProcess.destroy();
}
String sshEndCmd = String.format("cd %s && ./%s 1> /dev/null", monitorDir, monitorScript);
String sshCmd = "ssh";
String sshConnection = String.format("%s@%s", sshUser, dbHost);
String cmd = "";
cmd += String.format("export DSTAT_MYSQL_USER=%s;", dbUser);
cmd += String.format("export DSTAT_MYSQL_PWD=%s;", dbPassword);
cmd += String.format("export DSTAT_MYSQL_HOST=%s;", dbHost);
cmd += String.format("export DSTAT_MYSQL_PORT=%s;", dbPort);
cmd += String.format("export DSTAT_OUTPUT_PATH=%s;", "/dev/fd/2");
cmd += sshEndCmd;
String[] cmds = {sshCmd, sshConnection, cmd};
ProcessBuilder pb = new ProcessBuilder(cmds);
logFile = new File(logPath + File.separator + String.format("sys.log.%s", name));
pb.redirectErrorStream(true);
pb.redirectOutput(ProcessBuilder.Redirect.to(logFile));
monitorProcess = pb.start();
// start tailer
if (tailerExecutor != null)
{
tailerExecutor.shutdownNow();
}
logTailerListener = new LogTailerListener(logQueue, false);
logTailer = new LogTailer(logFile, logTailerListener, 250, 0, false);
tailerExecutor = Executors.newFixedThreadPool(1);
tailerExecutor.submit(logTailer);
Log.debug("dstat started remotely.");
}
public void stopMonitoring() throws Exception
{
if (monitorProcess != null)
{
monitorProcess.destroy();
}
if (tailerExecutor != null)
{
tailerExecutor.shutdownNow();
}
}
public String getDbName()
{
return dbName;
}
public void setDbName(String dbName)
{
this.dbName = dbName;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDbPort()
{
return dbPort;
}
public void setDbPort(String dbPort)
{
this.dbPort = dbPort;
}
public String getDbUser()
{
return dbUser;
}
public void setDbUser(String dbUser)
{
this.dbUser = dbUser;
}
public String getSshUser()
{
return sshUser;
}
public void setSshUser(String sshUser)
{
this.sshUser = sshUser;
}
public String getDbHost()
{
return dbHost;
}
public void setDbHost(String dbHost)
{
this.dbHost = dbHost;
}
public String getMonitorDir()
{
return monitorDir;
}
public void setMonitorDir(String monitorDir)
{
this.monitorDir = monitorDir;
}
public String getMonitorScript()
{
return monitorScript;
}
public void setMonitorScript(String monitorScript)
{
this.monitorScript = monitorScript;
}
public Process getMonitorProcess()
{
return monitorProcess;
}
public void setMonitorProcess(Process monitorProcess)
{
this.monitorProcess = monitorProcess;
}
public LogTailerListener getLogTailerListener()
{
return logTailerListener;
}
public LinkedBlockingQueue<String> getLogQueue()
{
return logQueue;
}
}
| ad7513123bacf5264c05f24b8b0f13e4a881a713 | [
"Markdown",
"Makefile",
"AsciiDoc",
"Java",
"Python",
"Ant Build System",
"Shell"
] | 76 | Java | dongyoungy/dbseer_middleware | ca1d4fbf29858d8cecc3154e0d1f02cdab5d6c67 | 711e070397471936fc0a4e2263f2c82a3dedc517 | |
refs/heads/main | <file_sep>import React from "react"
import Image from "gatsby-image"
const Bio = ({ author }) => {
return (
<div>
{author.avatar && (
<Image
fixed={author.avatar}
alt={author.name}
imgStyle={{
borderRadius: `50%`,
}}
/>
)}
{author.name && (
<p>
Written by <strong>{author.name}</strong> {author.summary || null}
</p>
)}
{author.social && (
<p>
<a href={author.url}>{author.social.name}</a>
</p>
)}
</div>
)
}
export default Bio
| 741a541d3dd70be34f4e803c105c90013d96c88e | [
"JavaScript"
] | 1 | JavaScript | luisduenas/gatsby-datocms-starter | d06dc8a783537ad650d82257930d58eb86cfbd06 | 5824b050fecf315dc24024494872ce0037bbb91b | |
refs/heads/master | <file_sep>import AppHeader from "@/components/AppHeader.vue"
import { shallowMount, createLocalVue, RouterLinkStub } from "@vue/test-utils"
import Vuex from "vuex"
const localVue = createLocalVue()
localVue.use(Vuex)
describe("AppHeader.vue", () => {
let $store
let wrapper
it("Displays board name if activeBoard is set", () => {
$store = {
dispatch: jest.fn(),
state: {},
getters: {
activeBoard: {
id: 222,
name: "tracker",
description: "tracker board",
archived: false,
lists: []
},
isLoading: jest.fn()
}
}
wrapper = shallowMount(AppHeader, {
mocks: { $store },
stubs: { RouterLink: RouterLinkStub }
})
expect(wrapper.text()).toContain("tracker")
})
it("display child component stubs when isLoading is false", () => {
$store = {
dispatch: jest.fn(),
state: {},
getters: {
isLoading: false,
activeBoard: {
id: 222,
name: "tracker",
description: "tracker board",
archived: false,
lists: [{ id: "222-1", name: "todo" }, { id: "222-2", name: "doing" }]
}
}
}
wrapper = shallowMount(AppHeader, {
mocks: { $store },
stubs: {
RouterLink: RouterLinkStub
}
})
expect(wrapper.contains("tasklistrestore-stub")).toBe(true)
expect(wrapper.contains("taskboardedit-stub")).toBe(true)
expect(wrapper.contains("tasklistarchive-stub")).toBe(true)
expect(wrapper.contains("tasklistedit-stub")).toBe(true)
})
it("does not render child component stubs when isLoading is true", () => {
$store = {
dispatch: jest.fn(),
state: {},
getters: {
isLoading: true,
activeBoard: {
id: 222,
name: "tracker",
description: "tracker board",
archived: false,
lists: [{ id: "222-1", name: "todo" }, { id: "222-2", name: "doing" }]
}
}
}
wrapper = shallowMount(AppHeader, {
mocks: { $store },
stubs: {
RouterLink: RouterLinkStub
}
})
expect(wrapper.contains("tasklistrestore-stub")).toBe(false)
expect(wrapper.contains("taskboardedit-stub")).toBe(false)
expect(wrapper.contains("tasklistarchive-stub")).toBe(false)
expect(wrapper.contains("tasklistedit-stub")).toBe(false)
})
})
<file_sep>import TaskListActions from "@/components/Lists/TaskListActions.vue"
import { mount, createLocalVue } from "@vue/test-utils"
import { Bus } from "@/utils/bus"
Bus.$emit = jest.fn()
describe("TaskListActions.vue", () => {
let wrapper
let propsData
beforeEach(() => {
propsData = {
board: { id: "222" },
list: { id: "222-2" }
}
wrapper = mount(TaskListActions, {
propsData: { board: propsData.board, list: propsData.list },
mocks: {},
stubs: {}
})
})
it("tasklist-editing event is triggered", () => {
wrapper.vm.showListEditPopup()
expect(Bus.$emit).toHaveBeenCalledWith("tasklist-editing", wrapper.vm.list)
})
it("tasklist-archiving event is triggered", () => {
wrapper.vm.showArchiveListPopup()
expect(Bus.$emit).toHaveBeenCalledWith("tasklist-archiving", { board: wrapper.vm.board, list: wrapper.vm.list })
})
})
<file_sep>import axios from "axios"
import actions from "@/store/actions"
jest.mock("axios")
describe("Test actions", () => {
const commit = jest.fn()
const payload = {}
it("fetchData", async () => {
const boards = [{}, {}]
const response = { data: { boards } }
axios.get.mockResolvedValue(response)
await actions.fetchData({ commit })
expect(commit).toHaveBeenCalledWith("SET_LOADING_STATE", true)
expect(commit).toHaveBeenCalledWith("SET_INITIAL_DATA", { boards })
expect(commit).toHaveBeenCalledWith("SET_LOADING_STATE", false)
})
it("saveTaskBoard", async () => {
await actions.saveTaskBoard({ commit }, payload)
expect(commit).toHaveBeenCalledWith("SAVE_TASKBOARD", payload)
})
it("archiveTaskBoard", async () => {
await actions.archiveTaskBoard({ commit }, payload)
expect(commit).toHaveBeenCalledWith("ARCHIVE_TASKBOARD", payload)
})
it("restoreTaskBoard", async () => {
await actions.restoreTaskBoard({ commit }, payload)
expect(commit).toHaveBeenCalledWith("RESTORE_TASKBOARD", payload)
})
it("setActiveTaskBoard", async () => {
await actions.setActiveTaskBoard({ commit }, payload)
expect(commit).toHaveBeenCalledWith("SET_ACTIVE_TASKBOARD", payload)
})
it("saveTaskList", async () => {
await actions.saveTaskList({ commit }, payload)
expect(commit).toHaveBeenCalledWith("SAVE_TASKLIST", payload)
})
it("archiveTaskList", async () => {
await actions.archiveTaskList({ commit }, payload)
expect(commit).toHaveBeenCalledWith("ARCHIVE_TASKLIST", payload)
})
it("restoreTaskList", async () => {
await actions.restoreTaskList({ commit }, payload)
expect(commit).toHaveBeenCalledWith("RESTORE_TASKLIST", payload)
})
it("reorderTaskLists", async () => {
await actions.reorderTaskLists({ commit }, payload)
expect(commit).toHaveBeenCalledWith("REORDER_TASKLISTS", payload)
})
it("reorderTaskListItems", async () => {
await actions.reorderTaskListItems({ commit }, payload)
expect(commit).toHaveBeenCalledWith("REORDER_TASKLIST_ITEMS", payload)
})
it("saveTaskListItem", async () => {
await actions.saveTaskListItem({ commit }, payload)
expect(commit).toHaveBeenCalledWith("SAVE_TASKLIST_ITEM", payload)
})
it("deleteTaskListItem", async () => {
await actions.deleteTaskListItem({ commit }, payload)
expect(commit).toHaveBeenCalledWith("DELETE_TASKLIST_ITEM", payload)
})
})
<file_sep>import TaskList from "@/components/Lists/TaskList.vue"
import { shallowMount, createLocalVue, RouterLinkStub } from "@vue/test-utils"
import Vuex from "vuex"
const localVue = createLocalVue()
localVue.use(Vuex)
describe("TaskList.vue", () => {
let $store
let wrapper
let board
beforeEach(() => {
board = {
id: 222,
name: "tracker",
description: "tracker board",
archived: false,
lists: [
{ id: "222-1", name: "todo", archived: false, headerColor: "#ddd", items: [] },
{
id: "222-2",
name: "doing",
archived: false,
headerColor: "#ddd",
items: [
{ id: "222-2-1", text: "This is a list item #1" },
{ id: "222-2-2", text: "This is a list item #2" },
{ id: "222-2-3", text: "This is a list item #3" }
]
}
]
}
$store = {
dispatch: jest.fn()
}
wrapper = shallowMount(TaskList, {
data() {
return {
isDesktop: true,
isTablet: false
}
},
propsData: { board: board, list: board.lists[1] },
mocks: { $store },
stubs: { RouterLink: RouterLinkStub }
})
})
it("dispatch reorderTaskListItems action when items computed property is updated", () => {
const listItems = [
{ id: "222-2-2", text: "This is a list item #2" },
{ id: "222-2-1", text: "This is a list item #1" },
{ id: "222-2-3", text: "This is a list item #3" }
]
wrapper.vm.items = listItems
expect($store.dispatch).toHaveBeenCalledWith("reorderTaskListItems", {
boardId: board.id,
listId: board.lists[1].id,
items: listItems
})
})
it("Should allow task items reorder on desktop or tablet", () => {
wrapper.vm.isDesktop = true
wrapper.vm.isTablet = false
expect(wrapper.vm.shouldAllowTaskItemsReorder).toBe(true)
})
it("Should not allow task items reorder if not on desktop or tablet", () => {
wrapper.vm.isDesktop = false
wrapper.vm.isTablet = false
expect(wrapper.vm.shouldAllowTaskItemsReorder).toBe(false)
})
it("Disable drag option while editing an list item", () => {
wrapper.vm.itemEditing()
wrapper.vm.isDesktop = true
wrapper.vm.isTablet = true
expect(wrapper.vm.dragOptions.disabled).toBe(true)
})
it("Enable drag option when list item is edited", () => {
wrapper.vm.itemEdited()
wrapper.vm.isDesktop = true
wrapper.vm.isTablet = true
expect(wrapper.vm.dragOptions.disabled).toBe(false)
})
it("Enable drag option when list item is edited", () => {
wrapper.vm.itemCancelled()
wrapper.vm.isDesktop = true
wrapper.vm.isTablet = true
expect(wrapper.vm.dragOptions.disabled).toBe(false)
})
})
<file_sep>import DetailsDropdown from "@/components/Details/DetailsDropdown"
import { shallowMount, createLocalVue, RouterLinkStub } from "@vue/test-utils"
describe("DetailsDropdown.vue", () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(DetailsDropdown, {
mocks: {},
stubs: {}
})
})
it("Open dropdown", () => {
wrapper.vm.open()
expect(
wrapper
.find("details")
.html()
.includes("open")
).toBe(true)
})
it("Close dropdown", () => {
wrapper.vm.close()
expect(
wrapper
.find("details")
.html()
.includes("open")
).toBe(false)
})
it("toggle check - open", () => {
wrapper.vm.open()
wrapper.find("details").trigger("toggle")
expect(wrapper.emitted("popup-toggled")).toBeTruthy()
})
it("toggle check - close", () => {
wrapper.vm.close()
wrapper.find("details").trigger("toggle")
expect(wrapper.emitted("popup-toggled")).toBeTruthy()
})
})
<file_sep>import TaskListItem from "@/components/Items/TaskListItem.vue"
import { shallowMount, createLocalVue, RouterLinkStub } from "@vue/test-utils"
import flushPromises from "flush-promises"
import Vuex from "vuex"
import VeeValidate from "vee-validate"
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VeeValidate)
describe("TasListItem.vue", () => {
let $store
let wrapper
let propsData
beforeEach(() => {
$store = {
dispatch: jest.fn()
}
propsData = {
item: { id: "222-1-1", text: "This is a list item" },
list: { id: "222-1" },
board: { id: "222" }
}
wrapper = shallowMount(TaskListItem, {
localVue,
propsData: propsData,
mocks: { $store },
stubs: { RouterLink: RouterLinkStub }
})
})
it("clears the form data", () => {
wrapper.setData({
form: {
id: "222-1-1",
text: "This is a list item"
}
})
wrapper.vm.clearForm()
expect(wrapper.vm.form.id).toBe("")
expect(wrapper.vm.form.text).toBe("")
})
it("saveTaskListItem action is called on save", async () => {
wrapper.vm.$validator.validateAll = jest.fn(() => Promise.resolve(true))
wrapper.vm.startEditing()
wrapper.vm.save()
await flushPromises()
expect(wrapper.vm.$validator.validateAll).toHaveBeenCalled()
expect($store.dispatch).toHaveBeenCalledWith("saveTaskListItem", {
boardId: propsData.board.id,
listId: propsData.list.id,
item: propsData.item
})
expect(wrapper.emitted("item-edited")).toBeTruthy()
})
it("does not call saveTaskListItem action, when form validation is failed", async () => {
wrapper.vm.$validator.validateAll = jest.fn(() => Promise.resolve(false))
wrapper.vm.startEditing()
wrapper.vm.save()
await flushPromises()
expect(wrapper.vm.$validator.validateAll).toHaveBeenCalled()
expect($store.dispatch).not.toHaveBeenCalled()
expect(wrapper.emitted("item-edited")).not.toBeTruthy()
})
it("emits 'item-editing' event when moving into edit mode", () => {
wrapper.vm.startEditing()
// Test if "item-editing event is emitted or not"
expect(wrapper.emitted("item-editing")).toBeTruthy()
})
it("emits 'item-cancelled' event when edit mode is cancelled", () => {
wrapper.vm.cancel()
// Test if "item-cancelled event is emitted or not"
expect(wrapper.emitted("item-cancelled")).toBeTruthy()
})
it("Calls 'deleteTaskListItem' action and emit 'item-deleted' event when remove method is called", () => {
wrapper.vm.remove()
// Test if "deleteTaskListItem" action have been called
// with appropriate arguments or not
expect($store.dispatch).toHaveBeenCalledWith("deleteTaskListItem", {
boardId: propsData.board.id,
listId: propsData.list.id,
item: propsData.item
})
// Test if "item-deleted event is emitted or not"
expect(wrapper.emitted("item-deleted")).toBeTruthy()
})
})
describe("Test computed properties", () => {
let wrapper
let propsData
beforeEach(() => {
propsData = {
item: { id: "", text: "" },
list: { id: "222-1" },
board: { id: "222" }
}
})
it("Displays '+ New Item'", () => {
wrapper = shallowMount(TaskListItem, {
localVue,
propsData: propsData,
stubs: { RouterLink: RouterLinkStub }
})
expect(wrapper.vm.displayText).toBe("+ New Item")
})
it("Displays 'This is a list item' when item is passed", () => {
propsData.item = { id: "222-1-1", text: "This is a list item" }
wrapper = shallowMount(TaskListItem, {
localVue,
propsData: propsData,
stubs: { RouterLink: RouterLinkStub }
})
expect(wrapper.vm.displayText).toBe("This is a list item")
})
})
<file_sep>import TaskBoardEdit from "@/components/Boards/TaskBoardEdit.vue"
import { mount, createLocalVue, RouterLinkStub } from "@vue/test-utils"
import flushPromises from "flush-promises"
import Vuex from "vuex"
import VeeValidate from "vee-validate"
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VeeValidate)
import { Bus } from "@/utils/bus"
Bus.$on = jest.fn()
describe("TaskBoardEdit.vue", () => {
let $store
let wrapper
beforeEach(() => {
$store = {
dispatch: jest.fn(),
getters: {
activeBoard: { id: "222" }
}
}
wrapper = mount(TaskBoardEdit, {
sync: false,
localVue,
mocks: { $store },
stubs: { RouterLink: RouterLinkStub }
})
})
it("clear boardForm data on handlePopupToggled", () => {
wrapper.vm.handlePopupToggled(false)
expect(wrapper.vm.boardForm.id).toBe(0)
expect(wrapper.vm.boardForm.name).toBe("")
expect(wrapper.vm.boardForm.description).toBe("")
})
it("does not clear boardForm data on handlePopupToggled", () => {
wrapper.setData({
boardForm: {
id: "222",
name: "tracker",
description: "tracker board"
}
})
wrapper.vm.handlePopupToggled(true)
expect(wrapper.vm.boardForm.id).toBe("222")
expect(wrapper.vm.boardForm.name).toBe("tracker")
expect(wrapper.vm.boardForm.description).toBe("tracker board")
})
it("listens for 'taskboard-editing' on event bus", () => {
Bus.$emit("taskboard-editing", {
id: "222",
name: "tracker",
description: "tracker board"
})
expect(Bus.$on).toHaveBeenCalledWith("taskboard-editing", wrapper.vm.handleTaskBoardEditing)
})
it("Heading property returns 'Create new board' if creating a new board", () => {
expect(wrapper.vm.heading).toBe("Create new board")
})
it("Heading property returns 'Update board information' if editing existing board", () => {
wrapper.setData({
boardForm: {
id: 222
}
})
expect(wrapper.vm.heading).toBe("Update board information")
})
it("saveTaskBoard action is called on handleSaveBoard", async () => {
const boardForm = {
id: "222",
name: "tracker",
description: "tracker board"
}
wrapper.vm.$validator.validateAll = jest.fn(() => Promise.resolve(true))
wrapper.vm.handleTaskBoardEditing(boardForm)
wrapper.vm.handleSaveBoard()
await flushPromises()
expect(wrapper.vm.$validator.validateAll).toHaveBeenCalled()
expect($store.dispatch).toHaveBeenCalledWith("saveTaskBoard", {
id: boardForm.id,
name: boardForm.name,
description: boardForm.description
})
})
})
<file_sep>import DetailsInline from "@/components/Details/DetailsInline"
import { shallowMount, createLocalVue, RouterLinkStub } from "@vue/test-utils"
describe("DetailsInline.vue", () => {
let wrapper
beforeEach(() => {
wrapper = shallowMount(DetailsInline, {
mocks: {},
stubs: {}
})
})
it("Open dropdown", () => {
wrapper.vm.open()
expect(
wrapper
.find("details")
.html()
.includes("open")
).toBe(true)
})
it("Close dropdown", () => {
wrapper.vm.close()
expect(
wrapper
.find("details")
.html()
.includes("open")
).toBe(false)
})
it("toggle check - open", () => {
wrapper.vm.open()
wrapper.find("details").trigger("toggle")
expect(wrapper.emitted("popup-toggled")).toBeTruthy()
})
it("toggle check - close", () => {
wrapper.vm.close()
wrapper.find("details").trigger("toggle")
expect(wrapper.emitted("popup-toggled")).toBeTruthy()
})
})
<file_sep># Task Management Application using Vue.js
A task managment board app built using Vue.js (Trello, JIRA style) for a project during my course.
I've added features such as user authentication system, assigning members and made some UX improvements apart from those covered in the tutorial.
Followed from the tutorial by techlab23 [Article Link](https://levelup.gitconnected.com/task-management-application-using-vue-js-part-1-df607ca30f48?gi=c51e20fc8189).
![Project Image](/docs/images/Screenshot.png)
## Build Setup
```bash
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run serve
# build for production with minification
npm run build
# run unit tests in watch mode
npm run test:unit
# run test coverage
npm run test:coverage
# To deploy your app on surge make sure you have surge cli
# installed globally on your machine.
# If you have it insalled already then feel free to skip this step
npm install -g surge
# Build and deploy the app on surge.sh in staging environment
# Note: Before running this command, please change the site url
# used for this command in package.json file.
npm run deploy-staging
# Build and deploy the app on surge.sh in production environment
# Note: Before running this command, please change the site url
# used for this command in package.json file.
npm run deploy
```
<file_sep>import getters from "@/store/getters"
describe("Vuex Getters", () => {
let state
beforeEach(() => {
state = {
isLoading: true,
activeBoard: {
id: "1234",
archived: false,
lists: [
{
id: "1234-1",
name: "Todo",
headerColor: "#607d8b",
archived: false,
items: []
}
]
},
boards: [
{
id: "123",
archived: true,
lists: [
{
id: "123-1",
name: "Todo",
headerColor: "#607d8b",
archived: false,
items: []
},
{
id: "123-2",
name: "Doing",
headerColor: "#607d8b",
archived: false,
items: []
}
]
},
{
id: "1234",
archived: false,
lists: [
{
id: "1234-1",
name: "Todo",
headerColor: "#607d8b",
archived: false,
items: []
}
]
}
]
}
})
it("isLoading", () => {
expect(getters.isLoading(state)).toBe(true)
})
it("allBoards", () => {
expect(getters.allBoards(state)).toBe(state.boards)
})
it("activeBoard", () => {
expect(getters.activeBoard(state)).toBe(state.activeBoard)
})
it("unarchivedBoards", () => {
const received = getters.unarchivedBoards(state)
const expected = state.boards.filter(b => !b.archived)
expect(received).toEqual(expected)
})
it("archivedBoards", () => {
const received = getters.archivedBoards(state)
const expected = state.boards.filter(b => b.archived)
expect(received).toEqual(expected)
})
it("archivedLists", () => {
const received = getters.archivedLists(state)
const expected = state.activeBoard.lists.filter(l => l.archived)
expect(received).toEqual(expected)
})
it("unarchivedLists", () => {
const received = getters.unarchivedLists(state)
const expected = state.activeBoard.lists.filter(l => !l.archived)
expect(received).toEqual(expected)
})
})
test("archivdLists returns blank array if activeBoard is not set", () => {
let state = { activeBoard: null }
const received = getters.archivedLists(state)
const expected = []
expect(received).toEqual(expected)
})
test("unarchivdLists returns blank array if activeBoard is not set", () => {
let state = { activeBoard: null }
const received = getters.unarchivedLists(state)
const expected = []
expect(received).toEqual(expected)
})
| 7e52d06042c66b1dff60ab99cb8bbefe30803293 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | Hansel-Christopher/project-management-app-vuejs | bfbd494516c981d56129afc61c01b0e0319c6915 | c6bae901d6d7bedfebebce87739849a1f3af03a4 | |
refs/heads/master | <file_sep>
$(window).scroll(function(){
let scrollTop =$(window).scrollTop();
if(scrollTop > 600)
{
$("#btnUp").fadeIn(500);
}
else
$("#btnUp").fadeOut(520);
})
$("#btnUp").click(function(){
$("body").animate({ scrollTop:0} , 1500)
})
$("a[href='#Login']").click(function(){
let LoginOffest = $("#Login").offset().top;
$("body,html").animate({scrollTop:LoginOffest},1000)
})
$("a[href='#SignUp']").click(function(){
let SignUpOffest = $("#SignUp").offset().top;
$("body,html").animate({scrollTop:SignUpOffest},1200)
})
$("a[href='#About']").click(function(){
let AboutOffest = $("#About").offset().top;
$("body,html").animate({scrollTop:AboutOffest},1400)
})
$("a[href='#Servises']").click(function(){
let ServisesOffest = $("#Servises").offset().top;
$("body,html").animate({scrollTop:ServisesOffest},1600)
})
$("a[href='#Features']").click(function(){
let FeaturesOffest = $("#Features").offset().top;
$("body,html").animate({scrollTop:FeaturesOffest},1800)
})
$("a[href='#Contact']").click(function(){
let ContactOffest = $("#Contact").offset().top;
$("body,html").animate({scrollTop:ContactOffest},2000)
})
/*
$("a").click(function(){
let aHref =$(this).attr("href")
let ContactOffest = $("#aHref").offset().top;
$("body,html").animate({scrollTop:ContactOffest},2000)
})
*/
| 7519b12bb7db75b8e81dadeaa10be5a0bdcadc41 | [
"JavaScript"
] | 1 | JavaScript | salmanelzaydy/Our-project-sticky-notice- | 0badcb6d7f3313f39f4a08a822504f5da19ffffe | f045c301513cddb171105f7ea245e232c11026f0 | |
refs/heads/master | <file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform } from 'ionic-angular';
import { InAppBrowser } from '@ionic-native/in-app-browser'
/**
* Generated class for the VideoTuitionPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-video-tuition',
templateUrl: 'video-tuition.html',
})
export class VideoTuitionPage {
constructor(public navCtrl: NavController, public navParams: NavParams, public platform: Platform, private iab: InAppBrowser) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad VideoTuitionPage');
}
openUrl(){
//this. platform.ready().then(() => {
const browser = this. iab.create('https://www.numberprep.com/online-tutoring/', '_self', 'location= yes');
browser.show();
// });
}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import 'rxjs/add/operator/map';
import * as firebase from 'firebase/app';
import { Storage } from '@ionic/storage';
@Injectable()
export class AuthServiceProvider {
public fireAuth: any;
userData= firebase.database().ref('/userProfile');
userCredit:number=0;
acredit:any;
constructor(public af: AngularFireAuth, public storage:Storage) {
this.fireAuth = firebase.auth();
console.log('Hello AuthServiceProvider Provider');
}
doLogin(email: string, password: string): firebase.Promise<any> {
return this.fireAuth.signInWithEmailAndPassword(email, password);
}
register(email: string, password: string, fullname: string, age: number, year: string, schoolname: string): firebase.Promise<any> {
return this.fireAuth.createUserWithEmailAndPassword(email, password)
.then((newUser) => {this.userData.child(this.fireAuth.currentUser.uid).set({
email:email,
fullname:fullname,
age:age,
year:year,
schoolname:schoolname,
usercredit:this.userCredit,
photoUrl:'https://firebasestorage.googleapis.com/v0/b/numberapp-dbbb6.appspot.com/o/marguerite-daisy-beautiful-beauty.jpg?alt=media&token=<PASSWORD>'});
this.storage.set('userInfo', JSON.stringify(newUser));
// firebase.database().ref('userProfile').child(newUser.uid).set({email: email});
});
}
updateimage(imageurl) {
var promise = new Promise((resolve, reject) => {
this.fireAuth.currentUser.updateProfile({
displayName: this.fireAuth.currentUser.fullname,
photoURL: imageurl
}).then(() => {
this.userData.child(this.fireAuth.currentUser.uid).update({
fullname: this.fireAuth.currentUser.fullname,
photoURL: imageurl,
uid: firebase.auth().currentUser.uid
}).then(() => {
resolve({ success: true });
}).catch((err) => {
reject(err);
})
}).catch((err) => {
reject(err);
})
})
return promise;
}
onfetchdata(){
var promise= new Promise((resolve,reject)=> {
this.userData.child(this.fireAuth.currentUser.uid).once('value',(snapshot) => {
resolve(snapshot.val());
}).catch ((err) => {
reject(err);
})
})
return promise;
}
resetPassword(email: string): any {
return this.fireAuth.sendPasswordResetEmail(email);
}
doLogout(): any {
return this.fireAuth.signOut();
}
}
<file_sep>import { Component } from '@angular/core';
/**
* Generated class for the ChatBubbleComponent component.
*
* See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
* for more info on Angular Components.
*/
@Component({
selector: 'chat-bubble',
inputs: ['msg: message'],
templateUrl: 'chat-bubble.html'
})
export class ChatBubbleComponent {
/** text: string;
constructor() {
console.log('Hello ChatBubbleComponent Component');
this.text = 'Hello World';
}
*/
public msg: any;
constructor() {
this.msg = {
content: 'Welcome, How may i help you?',
isMe: true,
time: '14/07/2017',
type:'text',
senderName: 'NumberPrep'
}
}
}
<file_sep>import { Component, NgZone } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { ImghandlerProvider } from '../../providers/imghandler/imghandler';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
/**
* Generated class for the ProfilePage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-profile',
templateUrl: 'profile.html',
})
export class ProfilePage {
avatar: string;
fullname: string;
constructor(public navCtrl: NavController, public navParams: NavParams,
public uprovider:AuthServiceProvider, public zone: NgZone, public alertCtrl: AlertController,
public imghandler: ImghandlerProvider) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad ProfilePage');
this.loaduserdetails();
}
loaduserdetails(){
this.uprovider.onfetchdata().then((res: any) => {
this.fullname = res.fullname;
this.zone.run(() => {
this.avatar = res.photoURL;
})
})
}
editimage() {
let statusalert = this.alertCtrl.create({
buttons: ['okay']
});
this.imghandler.uploadimage().then((url: any) => {
this.uprovider.updateimage(url).then((res: any) => {
if (res.success) {
statusalert.setTitle('Updated');
statusalert.setSubTitle('Your profile pic has been changed successfully!!');
statusalert.present();
this.zone.run(() => {
this.avatar = url;
})
}
}).catch((err) => {
statusalert.setTitle('Failed');
statusalert.setSubTitle('Your profile pic was not changed');
statusalert.present();
})
})
}
}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, AlertController, NavParams, LoadingController } from 'ionic-angular';
import { FormBuilder, Validators } from '@angular/forms';
import { AuthServiceProvider} from '../../providers/auth-service/auth-service';
import { HomePage } from '../home/home';
import { RegisterPage } from '../register/register';
import { TutorLoginPage } from '../tutor-login/tutor-login';
@IonicPage({
name: 'login'
})
@Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
public loginForm;
emailChanged: boolean = false;
passwordChanged: boolean = false;
submitAttempt: boolean = false;
loading: any;
constructor(public navCtrl: NavController, public authService: AuthServiceProvider, public navParams: NavParams,
public formBuilder: FormBuilder, public alertCtrl: AlertController, public loadingCtrl: LoadingController) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
this.loginForm = formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.pattern(EMAIL_REGEXP)])],
password: ['', Validators.compose([Validators.minLength(6), Validators.required])]
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
loginUser(){
this.submitAttempt = true;
if (!this.loginForm.valid){
console.log(this.loginForm.value);
} else {
this.authService.doLogin(this.loginForm.value.email, this.loginForm.value.password).then( authService => {
this.navCtrl.setRoot(HomePage);
}, error => {
this.loading.dismiss().then( () => {
let alert = this.alertCtrl.create({
message: error.message,
buttons: [
{
text: "Ok",
role: 'cancel'
}
]
});
alert.present();
});
});
this.loading = this.loadingCtrl.create({
dismissOnPageChange: true,
});
this.loading.present();
}
}
goToRegister(): void { this.navCtrl.push(RegisterPage);}
gotoTutorlogin(): void{this.navCtrl.push(TutorLoginPage);}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFireDatabase} from 'angularfire2/database';
import { Storage } from '@ionic/storage';
import { Camera } from '@ionic-native/camera';
import { Http } from '@angular/http';
import * as firebase from 'firebase/app';
import 'rxjs/add/operator/map';
/*
Generated class for the UserProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular DI.
*/
@Injectable()
export class UserProvider {
m:any;
constructor(public http: Http, public angFire:AngularFireDatabase,
private camera:Camera, public local:Storage) {
console.log('Hello UserProvider Provider');
}
//get Current User's UID
getUid(){
return this.local.get('userInfo').then(value => {
let newValue=JSON.parse(value);
return newValue.uid;
});
}
getCurrentUser(){
var uId=firebase.auth().currentUser.uid;
return uId;
}
/*getTutorId(tutor:string){
var query= firebase.database().ref('tutors').orderByChild('email').equalTo(tutor);
query.once("value",(snapshot) => {
snapshot.forEach((childSnapshot)=>{
console.log(childSnapshot.key);
//return tvalue;
});
});
}*/
}
<file_sep>import { Component, ViewChild, Renderer } from '@angular/core';
import { IonicPage, NavController, NavParams, Content, Platform} from 'ionic-angular';
import { Keyboard } from '@ionic-native/keyboard';
import { ImagePicker } from '@ionic-native/image-picker';
import { Camera} from '@ionic-native/camera';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import { UserProvider } from '../../providers/user/user-provider';
import {ChatProvider} from '../../providers/chat/chat-provider';
//import { AngularFireAuth } from 'angularfire2/auth';
//import * as firebase from 'firebase/app';
/**
* Generated class for the ChatViewPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-chat-view',
templateUrl: 'chat-view.html',
})
export class ChatViewPage {
//message:string;
uid:string;
interlocutor:string;
username:string;
chats:FirebaseListObservable<any>;
@ViewChild(Content)content:Content;
private inputElement;
private millis = 200;
private scrollTimeout = this.millis + 50;
private textareaHeight;
private scrollContentElelment: any;
private footerElement: any;
private initialTextAreaHeight;
private keyboardHideSub;
private keybaordShowSub;
user:boolean;
userid:string;
private message = "";
constructor(private camera: Camera, private keyboard: Keyboard, private imagePicker: ImagePicker,
public platform: Platform, public renderer: Renderer,
public navCtrl: NavController, public navParams: NavParams,
public angFire:AngularFireDatabase, public chatprov:ChatProvider,
public userprov:UserProvider)
{
this.uid = navParams.get('uid');
this.interlocutor = navParams.get('interlocutor');
this.username = navParams.get('name');
chatprov.getChatRef(this.uid,this.interlocutor).then((chatRef:any)=>
{
this.chats =this.angFire.list(chatRef);
});
}
ionViewDidLoad() {
this.updateScroll('load', 500)
if (this.platform.is('ios')) {
this.addKeyboardListeners()
}
this.scrollContentElelment = this.content.getScrollElement();
this.footerElement = document.getElementsByTagName('page-chat-view')[0].getElementsByTagName('ion-footer')[0];
this.inputElement = document.getElementsByTagName('page-chat-view')[0].getElementsByTagName('textarea')[0];
this.footerElement.style.cssText = this.footerElement.style.cssText + "transition: all " + this.millis + "ms; -webkit-transition: all " +
this.millis + "ms; -webkit-transition-timing-function: ease-out; transition-timing-function: ease-out;"
this.scrollContentElelment.style.cssText = this.scrollContentElelment.style.cssText + "transition: all " + this.millis + "ms; -webkit-transition: all " +
this.millis + "ms; -webkit-transition-timing-function: ease-out; transition-timing-function: ease-out;"
this.textareaHeight = Number(this.inputElement.style.height.replace('px', ''));
this.initialTextAreaHeight = this.textareaHeight;
}
addKeyboardListeners() {
this.keyboardHideSub = this.keyboard.onKeyboardHide().subscribe(() => {
let newHeight = this.textareaHeight - this.initialTextAreaHeight + 44;
let marginBottom = newHeight + 'px';
console.log('marginBottom', marginBottom)
this.renderer.setElementStyle(this.scrollContentElelment, 'marginBottom', marginBottom);
this.renderer.setElementStyle(this.footerElement, 'marginBottom', '0px')
});
this.keybaordShowSub = this.keyboard.onKeyboardShow().subscribe((e) => {
let newHeight = (e['keyboardHeight']) + this.textareaHeight - this.initialTextAreaHeight;
let marginBottom = newHeight + 44 + 'px';
console.log('marginBottom', marginBottom)
this.renderer.setElementStyle(this.scrollContentElelment, 'marginBottom', marginBottom);
this.renderer.setElementStyle(this.footerElement, 'marginBottom', e['keyboardHeight'] + 'px');
this.updateScroll('keybaord show', this.scrollTimeout);
});
}
footerTouchStart(event) {
//console.log('footerTouchStart: ', event.type, event.target.localName, '...')
if (event.target.localName !== "textarea") {
event.preventDefault();
// console.log('preventing')
}
}
contentMouseDown(event) {
//console.log('blurring input element :- > event type:', event.type);
this.inputElement.blur();
}
textAreaChange() {
let newHeight = Number(this.inputElement.style.height.replace('px', ''));
if (newHeight !== this.textareaHeight) {
let diffHeight = newHeight - this.textareaHeight;
this.textareaHeight = newHeight;
let newNumber = Number(this.scrollContentElelment.style.marginBottom.replace('px', '')) + diffHeight;
let marginBottom = newNumber + 'px';
this.renderer.setElementStyle(this.scrollContentElelment, 'marginBottom', marginBottom);
this.updateScroll('textAreaChange', this.scrollTimeout);
}
}
updateScroll(from, timeout) {
setTimeout(() => {
//console.log('updating scroll -->', from)
this.content.scrollToBottom();
}, timeout);
}
ionViewDidEnter() {
this.content.scrollToBottom(300);
}
/** sendMessage(){
if(this.message){
let chat={
from:this.uid,
message:this.message,
type:'message',
timestamp: new Date()
};
this.chats.push(chat);
this.message = "";
}
};**/
sendMessage() {
this.user = this.uid === this.userprov.getCurrentUser();
this.addMessage(this.user, this.message);
this.message = "";
//this.user=false;
let currentHeight = this.scrollContentElelment.style.marginBottom.replace('px', '');
let newHeight = currentHeight - this.textareaHeight + this.initialTextAreaHeight;
let top = newHeight + 'px';
this.renderer.setElementStyle(this.scrollContentElelment, 'marginBottom', top);
this.updateScroll('sendMessage', this.scrollTimeout);
this.textareaHeight = this.initialTextAreaHeight;
setTimeout(() => {
this.content.scrollToBottom(300);
});
}
addMessage(id, msg) {
this.chats.push({
from: this.uid,
isMe:id,
body: msg,
timestamp: new Date().toISOString(),
type:'message'
});
}
/*sendPicture(){
let chat = {
from:this.uid,
type:'picture',
picture:null};
}*/
sendImage(){
let camerOptions = {
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
saveToPhotoAlbum: true,
targetWidth: 1000,
targetHeight: 1000,
correctOrientation: true //Corrects Android orientation quirks
}
this.camera.getPicture(camerOptions).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.user = this.uid === this.userprov.getCurrentUser();
this.addImage(this.user, base64Image);
console.log(base64Image);
this.updateScroll('image add', this.millis)
}, (err) => {
// Handle error
});
}
captureImage(){
let camerOptions = {
quality: 50,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
sourceType: this.camera.PictureSourceType.CAMERA,
allowEdit: true,
saveToPhotoAlbum: true,
targetWidth: 1000,
targetHeight: 1000,
correctOrientation: true //Corrects Android orientation quirks
}
this.camera.getPicture(camerOptions).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
let base64Image = 'data:image/jpeg;base64,' + imageData;
this.user = this.uid === this.userprov.getCurrentUser();
this.addImage(this.user, base64Image);
console.log(base64Image);
this.updateScroll('image add', this.millis)
}, (err) => {
// Handle error
});
}
addImage(id, imgData) {
this.chats.push({
from:this.uid,
isMe:id,
img: imgData,
type:'picture',
timestamp: new Date()
});
}
}
<file_sep>import { Component } from '@angular/core';
import { App, IonicPage, NavController, NavParams } from 'ionic-angular';
import { AuthServiceProvider} from '../../providers/auth-service/auth-service';
import { LoginPage } from '../login/login';
/**
* Generated class for the LogOutPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-log-out',
templateUrl: 'log-out.html',
})
export class LogOutPage {
constructor(public app:App, public navCtrl: NavController, public navParams: NavParams, public authprovider:AuthServiceProvider ) {
}
ionViewDidLoad() {
this.authprovider.doLogout().then(authprovider => {
let nav = this.app.getRootNav();
nav.setRoot(LoginPage);});
}
}
<file_sep><!--
Generated template for the VideoTuitionPage page.
See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>VideoTuition</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<p> Please, click on the button below to have access to get access to our video tuition. </p>
<button ion-button="" large="" color="primary" (click)="openUrl()" >Video Tuition</button>
</ion-content>
<file_sep>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { VideoTuitionPage } from './video-tuition';
@NgModule({
declarations: [
VideoTuitionPage,
],
imports: [
IonicPageModule.forChild(VideoTuitionPage),
],
exports: [
VideoTuitionPage
]
})
export class VideoTuitionPageModule {}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import firebase from 'firebase';
import { AngularFireAuth } from 'angularfire2/auth';
import { UserProvider } from '../../providers/user/user-provider';
import { AuthServiceProvider} from '../../providers/auth-service/auth-service';
/**
* Generated class for the BuycreditPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-buycredit',
templateUrl: 'buycredit.html',
})
export class BuycreditPage {
public fireAuth: any;
credit:any;
userId:any;
userData= firebase.database().ref('/userProfile');
public newvalue: number;
constructor(public navCtrl: NavController, public navParams: NavParams,
public af: AngularFireAuth, public authService: AuthServiceProvider, public user:UserProvider) {
this.fireAuth = firebase.auth();
}
ionViewDidLoad() {
console.log('ionViewDidLoad BuycreditPage');
this.loadusercredit();
}
loadusercredit(){
this.authService.onfetchdata().then((res:any)=>{
this.newvalue = res.usercredit;
})
}
add5(){
this.credit=this.newvalue + 50;
this.userData.child(this.fireAuth.currentUser.uid).update({usercredit:this.credit});
}
add10(){
this.credit=this.newvalue + 100;
this.userData.child(this.fireAuth.currentUser.uid).update({usercredit:this.credit});
}
add15(){
this.credit=this.newvalue + 150;
this.userData.child(this.fireAuth.currentUser.uid).update({usercredit:this.credit});
}
add20(){
this.credit=this.newvalue + 200;
this.userData.child(this.fireAuth.currentUser.uid).update({usercredit:this.credit});
}
}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavParams } from 'ionic-angular';
//import {ChatViewPage} from '../../pages/chat-view/chat-view';
import {ChatsPage} from '../../pages/chats/chats';
import {LogOutPage} from '../../pages/log-out/log-out';
@IonicPage()
@Component({
selector: 'page-tutor-tabs',
templateUrl: 'tutor-tabs.html',
})
export class TutorTabsPage {
myTutor:any;
//tab1Root:any = ChatViewPage;
tab1Root:any = ChatsPage;
tab2Root:any = LogOutPage;
tab2Params:any;
constructor(public navParams:NavParams) {
this.myTutor=navParams.get('tutormail')
this.tab2Params={id:this.myTutor};
}
}
<file_sep>import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import {UserProvider} from '../../providers/user/user-provider';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the ChatProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular DI.
*/
@Injectable()
export class ChatProvider {
constructor(public http: Http, public angfire:AngularFireDatabase, public userprovider:UserProvider)
{
console.log('Hello ChatProvider Provider');
}
//get list of chat of a logged in user
getChats(){
return this. userprovider.getUid().then(uid => {
let chats = this.angfire.list(`/userProfile/${uid}/chats`);
return chats;
});
}
//add chat reference to both users
addChats(uid,interlocutor){
// First User
//let otherUid = interlocutor;
let endpoint =
this.angfire.object(`userProfile/${uid}/chats/${interlocutor}`);
endpoint.set(true);
// Second User
let endpoint2 =
this.angfire.object(`tutors/${interlocutor}/chats/${uid}`);
endpoint2.set(true);
}
getChatRef(uid, interlocutor) {
let firstRef =
this.angfire.object(`userProfile/${uid}/chats/${interlocutor}`,{preserveSnapshot:true});
let promise = new Promise((resolve, reject) => {
firstRef.subscribe(snapshot => {
let a = snapshot.exists();
if(a) {
resolve(`/chats/${interlocutor},${uid}`);
}
else {
let secondRef = this.angfire.object(`tutors/${uid}/chats/${interlocutor}`, {preserveSnapshot:true});
secondRef.subscribe(snapshot => {
let b = snapshot.exists();
if(b) {
resolve(`/chats/${uid},${interlocutor}`);
}
else{
this.addChats(uid,interlocutor);
resolve(`/chats/${interlocutor},${uid}`);
}
});
}
});
});
return promise;
}
}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, AlertController, NavParams, LoadingController } from 'ionic-angular';
import { FormBuilder, Validators } from '@angular/forms';
import { AuthServiceProvider} from '../../providers/auth-service/auth-service';
import {TutorTabsPage} from '../tutor-tabs/tutor-tabs';
/**
* Generated class for the TutorLoginPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-tutor-login',
templateUrl: 'tutor-login.html',
})
export class TutorLoginPage {
public tutorForm;
submitAttempt: boolean = false;
loading: any;
constructor(public navCtrl: NavController, public authService: AuthServiceProvider, public navParams: NavParams,
public formBuilder: FormBuilder, public alertCtrl: AlertController, public loadingCtrl: LoadingController) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
this.tutorForm = formBuilder.group({
email: ['', Validators.compose([Validators.required, Validators.pattern(EMAIL_REGEXP)])],
password: ['', Validators.compose([Validators.minLength(6), Validators.required])]
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad TutorLoginPage');
}
loginTutor(){
this.submitAttempt = true;
if (!this.tutorForm.valid){
console.log(this.tutorForm.value);
} else {
this.authService.doLogin(this.tutorForm.value.email, this.tutorForm.value.password).then( authService => {
this.navCtrl.push(TutorTabsPage,{tutormail:this.tutorForm.value.email});
}, error => {
this.loading.dismiss().then( () => {
let alert = this.alertCtrl.create({
message: error.message,
buttons: [
{
text: "Ok",
role: 'cancel'
}
]
});
alert.present();
});
});
this.loading = this.loadingCtrl.create({
dismissOnPageChange: true,
});
this.loading.present();
}
}
}
<file_sep>import { Component } from '@angular/core';
import { NavController, ModalController, Platform } from 'ionic-angular';
import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database';
import 'rxjs/add/operator/map';
import { TutorsPage } from '../tutors/tutors';
@Component({
selector: 'page-ask-question',
templateUrl: 'ask-question.html',
})
export class AskQuestionPage {
public topics : FirebaseListObservable<any[]>;
selectedItem: any;
icons: string[];
items: Array<{title: string, note: string, icon: string}>;
constructor(public navCtrl : NavController,
private angFire : AngularFireDatabase,
private modalCtrl : ModalController,
private platform : Platform)
{
}
ionViewDidLoad()
{
this.platform.ready()
.then(() =>
{
this.topics = this.angFire.list('/topics');
});
}
listtutors(topic){
this.navCtrl.push(TutorsPage, {topic : topic});
//let params = { topic: topic },
//tutormodal = this.modalCtrl.create( TutorsPage, params);
//tutormodal.present();
}
}
<file_sep>import { Component, NgZone } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {Observable} from 'rxjs/Rx';
import { UserProvider } from '../../providers/user/user-provider';
import { AngularFireDatabase } from 'angularfire2/database';
import {ChatViewPage} from '../../pages/chat-view/chat-view';
import * as firebase from 'firebase/app';
/**
* Generated class for the ChatsPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
export interface Detail {
// Property (public by default)
key:string;
username: string;
email: string;
}
@IonicPage()
@Component({
selector: 'page-chats',
templateUrl: 'chats.html',
})
export class ChatsPage {
tutorID:any;
myTutor:any;
query:any;
query1: any;
query2:any;
interlocutor:string;
chats:Observable<any[]>;
studentdetail: Detail[]=[];
constructor(public navCtrl: NavController, public navParams: NavParams, public user:UserProvider,
public angfire:AngularFireDatabase, public zone: NgZone) {
this.myTutor=navParams.get('id');
this.query= firebase.database().ref('tutors').orderByChild('email').equalTo(this.myTutor);
//this.getChats().then(chats => {
/*this.chats=this.getChats().map(users =>{
return users.map(user =>{
user.info = this.angfire.object(`/userProfile/${user.$key}`);
return user;
});
});*/
//});
}
ngOnInit(){
//gets tutor's ID
this.query.once("value",(snapshot) => {
snapshot.forEach((childSnapshot)=>{
var tvalue= childSnapshot.key;
//console.log("first",tvalue);
this.tutorID = tvalue;
//console.log('second', this.tutorID);
this.getChats(this.tutorID);
});
});
}
//get Tutor's chats list
getChats(ttutor){
var userRef=firebase.database().ref('userProfile/')
this.query2=firebase.database().ref('tutors/' + ttutor + '/chats');
this.query2.on('value',(snapshot)=> {
this.zone.run(()=> {
snapshot.forEach((childSnapshot)=>{
//var childKey = childSnapshot.key;
//var childData = childSnapshot.val();
//console.log("The " + childKey + " student " + childData);
userRef.child(childSnapshot.key).on('value',(data)=>{
//var stkey= data.key;
//var stdata = data.val();
//console.log(data.key, 'name', data.val().fullname);
this.getDetails(data.key, data.val().fullname, data.val().email);
});
});
});
});
}
//get student details
getDetails(data1, data2, data3){
this.studentdetail.push({
key:data1,
username:data2,
email:data3
});
}
openChat(key, username){
this. navCtrl.push(ChatViewPage, {uid:this.tutorID, interlocutor:key, name: username});
}
}
<file_sep>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase} from 'angularfire2/database';
import { UserProvider } from '../../providers/user/user-provider';
import {ChatViewPage} from '../../pages/chat-view/chat-view';
@IonicPage()
@Component({
selector: 'page-tutors',
templateUrl: 'tutors.html',
})
export class TutorsPage {
//public topics : FirebaseListObservable<any[]>;
public topictitle : any = '';
public topictutors : any = [];
uid:string;
public tutorID: any;
constructor(public navCtrl: NavController, private angFire:AngularFireDatabase,
public params: NavParams, public user:UserProvider)
{
//this.topics = this.angFire.list('/topics');
let topic = params.get('topic');
let k;
for(k in topic.tutors)
{
this.topictitle = topic.title;
this.topictutors.push(topic.tutors[k].name);
}
this.uid= user.getCurrentUser();
}
ionViewDidLoad() {
console.log('ionViewDidLoad TutorsPage');
}
openChat(key){
this. navCtrl.push(ChatViewPage, {uid:this.uid, interlocutor:key, name:key});
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { AngularFireModule } from 'angularfire2';
import { AngularFireAuthModule} from 'angularfire2/auth';
import { AngularFireDatabaseModule} from 'angularfire2/database';
import { HttpModule } from '@angular/http';
import { Camera} from '@ionic-native/camera';
import { Keyboard } from '@ionic-native/keyboard';
import { ImagePicker } from '@ionic-native/image-picker';
import {IonicStorageModule} from '@ionic/storage';
import {FileChooser} from '@ionic-native/file-chooser';
import { InAppBrowser } from '@ionic-native/in-app-browser'
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { AskQuestionPage } from '../pages/ask-question/ask-question';
import {LoginPage} from '../pages/login/login';
import { RegisterPage } from '../pages/register/register';
import {BuycreditPage} from '../pages/buycredit/buycredit';
import {TutorsPage} from '../pages/tutors/tutors';
import {ChatViewPage} from '../pages/chat-view/chat-view';
import {LogOutPage} from '../pages/log-out/log-out';
import {ChatsPage} from '../pages/chats/chats';
import {TutorLoginPage} from '../pages/tutor-login/tutor-login';
import {TutorTabsPage} from '../pages/tutor-tabs/tutor-tabs';
import {ProfilePage} from '../pages/profile/profile';
import {VideoTuitionPage} from '../pages/video-tuition/video-tuition';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AuthServiceProvider } from '../providers/auth-service/auth-service';
import { UserProvider } from '../providers/user/user-provider';
import { ChatProvider } from '../providers/chat/chat-provider';
import { ChatBubbleComponent } from '../components/chat-bubble/chat-bubble';
import { ImghandlerProvider } from '../providers/imghandler/imghandler';
import * as firebase from 'firebase/app';
// Initialize Firebase
export const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "numberapp-dbbb6.firebaseapp.com",
databaseURL: "https://numberapp-dbbb6.firebaseio.com",
projectId: "numberapp-dbbb6",
storageBucket: "numberapp-dbbb6.appspot.com",
messagingSenderId: "616363762415"
};
firebase.initializeApp(firebaseConfig);
@NgModule({
declarations: [
MyApp,
HomePage,
AskQuestionPage,
LoginPage,
BuycreditPage,
RegisterPage,
TutorsPage,
ChatViewPage,
LogOutPage,
ChatsPage,
TutorLoginPage,
TutorTabsPage,
ProfilePage,
VideoTuitionPage,
ChatBubbleComponent
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
AngularFireModule.initializeApp(firebaseConfig),
AngularFireAuthModule,
AngularFireDatabaseModule,
HttpModule,
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
AskQuestionPage,
LoginPage,
BuycreditPage,
RegisterPage,
TutorsPage,
ChatViewPage,
LogOutPage,
ChatsPage,
TutorLoginPage,
TutorTabsPage,
ProfilePage,
VideoTuitionPage
],
providers: [
StatusBar,
SplashScreen,
Camera,
Keyboard,
ImagePicker,
FileChooser,
InAppBrowser,
//Storage,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AuthServiceProvider,
UserProvider,
ChatProvider,
ImghandlerProvider
]
})
export class AppModule {}
| fff465fa491cd13814fdbfb8cc5be25414f28cbf | [
"TypeScript",
"HTML"
] | 18 | TypeScript | Dunsin/NumberApp | 138ea84844220bb96952111008ba220b591c49fa | d611e7d96443e56c377a5acfe549e34d4b81f1f1 | |
refs/heads/master | <file_sep>var path = require('path'),
rootPath = path.normalize(__dirname + '/..'),
env = process.env.NODE_ENV || 'production';
console.log('NODE_ENV == ',env)
var config = {
//开发者环境配置
development: {
root : rootPath,
port : 8011,
maxOrderTime: 1080,
app : {
name : 'foowala-test'
},
main : {
languagePath: rootPath + '/language/'
},
cookie : {
secret : 'foowala',
sessionName: 'session'
}
},
// 测试环境配置
test: {
root : rootPath,
port : 8011,
maxOrderTime: 1080,
app : {
name: 'foowala-test'
},
main: {
languagePath: rootPath + '/language/'
},
cookie : {
secret : 'foowala',
sessionName: 'session'
}
},
// 线上产品配置
production: {
root : rootPath,
port : 8011,
maxOrderTime: 1080,
app : {
name: 'foowala'
},
main: {
languagePath: rootPath + '/language/'
},
cookie : {
secret : 'foowala',
sessionName: 'session'
}
}
};
module.exports = config[env];
| daf9348e7a6d5956a93c82364e28c86a9e2bdce0 | [
"JavaScript"
] | 1 | JavaScript | a904616537/testm | 5fbdd8b5bf795b97f014ee09c5dee7d3845a0005 | 8c7f18f13384faa275cd49a2741b1c42d88fe341 | |
refs/heads/master | <repo_name>crollax/Rust<file_sep>/solo/src/ownership.rs
use std::vec;
pub fn run () {
// let x: u8 = 1;
// let mut s = String::from("A String");
// let x = 1;
// s.pop();
// println!("{}", s);
///////////////////////////////////////////////////
// Compiler will automatically make copies
/* Rust Stack | Copy types
bool, character, numbers, slices
fix sized arrays, touples containing primitives
function pointers
*/
let x = 10;
let y = x;
let z = x;
// println!("x = {}", x);
// println!("y = {}", y);
// println!("z = {}", z);
// copy(true);
// copy("a");
// copy("a slice");
// copy(x);
// copy(String::from("Test")); // causes error
///////////////////////////////////////////////////
let mut a = String::from("A String");
let x = &mut a;
let y = &mut a;
}
fn copy<T>(t: T) -> T
where // Guard
T: Copy, // T must ba able to implement Trait Copy
{
let x = t;
x
}
fn print(a: u8) {
println!("value {}", a);
}
fn re(v: Vec<i32>) -> Vec<i32> {
println!("{}", v[120] + v[111]);
v
}
fn borrow1(v: &Vec<i32>) {
// *v == pointer to the ref of the vector arg
println!("{}", (*v)[10] + (*v)[12]);
}
fn borrow2(v: &Vec<i32>) {
println!("{}", v[10] + v[11]);
}
fn count(v: &Vec<i32>, val: i32) -> usize {
v.into_iter().filter(|&&x| x == val).count()
}
pub fn run_2 () {
let mut v = Vec::new();
for i in 1..1000 {
v.push(i);
}
// Transfer ownership to re function and then back
v = re(v);
println!("Still own v: {} {}", v[0], v[1]);
borrow1(&v);
println!("Still own v: {} {}", v[0], v[1]);
borrow2(&v);
println!("Still own v: {} {}", v[0], v[1]);
let mut vs = vec![4,5,3,6,7,4,8,6,4,2,4,2,5,3,7,7];
// Need to sort before dedup
vs.sort();
println!("vs sorted: {:?}", &vs);
// Clone to new set var
let mut set = vs.clone();
// Create the set with dedup
set.dedup();
println!("set dedup: {:?}", &set);
println!("vs: {:?}", vs);
// &i destructures the &{integer} type for i
for &i in &set {
let r = count(&vs, i);
println!("{} is repeated {} times", i, r);
}
}<file_sep>/solo/src/traits.rs
trait Shape {
fn area(&self) -> u32;
}
struct Rectangle {
x: u32,
y: u32,
}
struct Circle {
radius: f64;
}
impl Shape for Rectangle {
fn area(&self) -> u32 {
self.x * self.y
}
}
impl Shape for Circle {
fn area(&self) -> u32 {
(3.141 * self.radius * self.radius) as u32
}
}
/////////////////////////////////////////////////////////////////////////
// Using generics
/////////////////////////////////////////////////////////////////////////
use std::ops::Mul;
trait Shape_2<T> {
fn area(&self) -> T;
}
struct Rectangle_2<T: Mul> {
x: T,
y: T,
}
// Where T uses mult triat and output must be of type T and implements Copy
impl <T:Mul<Output = T> + Copy> Shape_2<T> for Rectangle_2<T> {
fn area(&self) -> T {
self.x * self.y
}
}
// using copy trait makes all uses set to var a copy
// with clone must use .clone() syntax
#[derive(Debug, Clone, Copy)]
struct A(i32);
// comparison operator traits
#[derive(Eq, PartialEq, PartialOrd, Ord)]
struct B(f32);
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
pub fn run() {
}<file_sep>/solo/src/main.rs
#![allow(dead_code)]
// mod ipadd;
// mod message;
// mod coin;
// mod restaurant;
// mod trash;
// mod print;
// mod rectangle;
// mod arrays;
// mod vectors;
// mod conditionals;
// mod closures;
// mod minigrep;
// mod linkedlist;
// mod hashmaps;
// mod traits;
// mod ownership;
// mod structs;
// mod loops;
// mod matches;
// mod enums;
// mod options;
mod lifetimes;
fn main() {
lifetimes::run();
// closures::test();
// vectors::run_2();
// ownership::run_2();
// structs::run();
// loops::run();
// matches::run();
// enums::run();
// options::run();
// arrays::run();
// vectors::run();
// vectors::make_vecs();
// ipadd::ipadd();
// message::message();
// coin::coin();
// trash::option_match();
// restaurant::eat_at_restaurant();
// print::run();
// conditionals::run();
// closures::run();
// minigrep::run();
// linkedlist::run();
// hashmaps::run();
// traits::run();
// rectangle::test_rectangle();
}
<file_sep>/solo/src/hashmaps.rs
// HashMaps
// Need consistant types
use std::collections::HashMap;
// enum Score {
// Color,
// Value
// }
pub fn run () {
let mut scores = HashMap::new();
let mut hm = HashMap::new();
// let mut score = HashMap::new();
hm.insert(String::from("random"), 12);
hm.insert(String::from("strings"), 49);
for (k, v) in &hm {
println!("{}: {}", k, v);
}
// Use get method with key
// and destruct to gain access to value
let key = &String::from("random");
match hm.get(key) {
Some(&n) => println!("value: {}", n),
_ => println!("no match"),
}
scores.insert(String::from("Blue"), 10);
scores.insert(String::from("Yellow"), 50);
println!("HashMap scores {:?}", scores)
}<file_sep>/apts_api/src/main.rs
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
// #[macro_use]
extern crate rocket_contrib;
// #![macro_use]
extern crate mysql;
mod routes;
// mod examples;
// #[database("rocket_app")]
// pub struct DbConn(diesel::MysqlConnection);
fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![
routes::index,
routes::run_payments,
])
// .attach(DbConn::fairing())
}
fn main() {
rocket().launch();
}<file_sep>/apts_api/migrations/2019-12-12-154127_create_books/up.sql
-- Your SQL goes here
Create table books (
id int not null auto_increment,
title varchar(200) not null,
author varchar(200) not null,
published boolean not null default 0,
PRIMARY KEY(id)
);<file_sep>/apts_api/src/examples/mod.rs
pub mod payments;
pub fn run() {
payments::run();
}
pub fn run_payments() {
payments::run();
}<file_sep>/solo/src/options.rs
// Options -> Basic enum type
// enum Option<T> {
// Some(T),
// None,
// }
pub fn run () {
option_match();
}
fn option_match() {
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("{:?}, {:?}, {:?}", five, six, none);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}<file_sep>/solo/src/restaurant.rs
pub use crate::restaurant::front_of_house::hosting;
pub fn eat_at_restaurant() {
// front_of_house::hosting::add_to_waitlist();
hosting::add_to_waitlist();
front_of_house::serving::take_order("smothered and covered");
back_of_house::fix_incorrect_order();
let mut meal = back_of_house::Breakfast::summer("Rye");
meal.toast = String::from("Wheat");
println!("I'd like {} toast please", meal.toast);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
mod front_of_house {
pub mod hosting {
pub fn add_to_waitlist() {
println!("INSIDE of add_to_waitlist()");
}
fn _seat_at_table() {}
}
pub mod serving {
pub fn take_order(order:&str) {
println!("Taking this order: {}", &order);
}
fn _serve_order() {}
fn _take_payment() {}
}
}
fn serve_order() {
println!("INSIDE serve_order()");
}
mod back_of_house {
pub fn fix_incorrect_order() {
cook_order();
super::serve_order();
}
fn cook_order() {}
pub struct Breakfast {
pub toast: String,
seasonal_fruit: String,
}
impl Breakfast {
pub fn summer(toast:&str) -> Breakfast {
Breakfast {
toast: String::from(toast),
seasonal_fruit: String::from("peaches"),
}
}
}
}
<file_sep>/solo/src/ipadd.rs
pub fn ipadd() {
let home = IPAddrKind::V4(String::from("127.0.0.1"));
let loopback = IPAddrKind::V6(String::from("::1"));
}
enum IPAddrKind { // Type
V4(String),
V6(String),
}
<file_sep>/apts_api/src/routes.rs
use apts_api::examples;
#[get("/main")]
pub fn index() -> &'static str {
"Application successfully started!"
}
#[get("/payments")]
pub fn run_payments() -> &'static str {
examples::run_payments();
"Payments api call successfully called!"
}<file_sep>/solo/src/pointers.rs
pub fn run () {
using_ref();
}
fn using_ref () {
// using ref
let u = 10;
// the next two statements are equivlent
let v = &u;
let ref z = u;
if z == v {
println!("They are equal");
}
}<file_sep>/solo/src/matches.rs
// What if you want to match multiple arms?
//If let or While let
// Pattern matching
pub fn run_2 () {
let mut s = Some(0);
if let Some(i) = s {
println!("i: {}", i);
}
while let Some(i) = s {
if i > 19 {
println!("Quit");
s = None;
} else {
println!("{}", i);
s = Some(i + 2);
}
}
}
pub fn run () {
// clone_match();
check_shapes();
}
// Matching on values with no ownership
// sets value of p to n
fn clone_match () {
let p = 0;
let n = match p {
n @ 1 ..= 12 => n,
n @ 13 ..= 19 => n,
_ => 0,
};
println!("n: {}", n)
}
fn guard_match () {
let pair = (5, -5);
match pair {
(x, y) if x == y => println!("Equal"),
(x, y) if x + y == 0 => println!("Equal Zero"),
(x, _) if x % 2 == 0 => println!("X is even"),
_ => println!("No match"),
}
}
fn touple_match () {
let pair = (0, -2);
// Matches on the non var item
// Binds the var to the other param (destructures the touple)
match pair {
(0, y) => println!("y: {}", y),
(x, 0) => println!("x: {}", x),
_ => println!("No match"),
}
}
fn match1 () {
let x = 10;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
4 => println!("four"),
5 => println!("five"),
_ => println!("something else"),
}
}
fn match2 () {
let n = 15;
match n {
1 => println!("One!"),
// Conditional check
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13 ..= 19 => println!("A teen"),
_ => println!("Ain't special"),
}
}
enum Shape {
Rectangle {width: u32, height: u32},
Square(u32),
Circle(f64),
}
impl Shape{
fn area(&self) -> f64 {
match *self {
Shape::Rectangle {width, height} => (width * height) as f64,
Shape::Square(ref s) => (s * s) as f64,
Shape::Circle(ref r) => 3.14 * (r * r),
}
}
}
fn check_shapes () {
let r = Shape::Rectangle{width: 10, height: 70};
let s = Shape::Square(10);
let c = Shape::Circle(4.5);
let ar = r.area();
println!("{}", ar);
let aq = s.area();
println!("{}", aq);
let ac = c.area();
println!("{}", ac);
}
fn option_match() {
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
println!("{:?}, {:?}, {:?}", five, six, none);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
// Using a Result enum
use std::fs::File;
fn open_file() {
let f = File::open("test.txt");
let f = match f {
Ok(file) => file,
Err(error) => {
panic!("There was a problem opening the file: {:?}", error);
}
}
}<file_sep>/solo/src/closures.rs
use std::thread;
use std::time::Duration;
pub fn run () {
let intensity = 10;
let random_number = 5;
generate_workout(intensity, random_number)
}
pub fn test () {
let f = |i| i + 1;
let x = 10;
println!("{}", f(x));
let p = || println!("This is a closure");
p();
let k = create();
k();
// Closure inside of an iterator
let v = vec![1,2,3];
println!("is 2 in v? {}", v.iter().any(|&x| x != 2));
}
// Using move here is like using Copy trait
// as opposed to using a reference (&)
fn create () -> Box<Fn()> {
Box::new(move || println!("this is a closure in a box!"))
}
pub fn generate_workout(intensity: u32, random_number: u32) {
let expensive_closure = |num| {
println!("calculating slowly...");
thread::sleep(Duration::from_secs(2));
num
};
if intensity < 25 {
println!("Today do {} pushups!", expensive_closure(intensity));
println!("Next, do {} situps!", expensive_closure(intensity));
}
else {
if random_number == 3 {
println!("Take a break today! Remember to stay hydrated!");
}
else {
println!("Today, run for {} minutes!", expensive_closure(intensity));
}
}
}<file_sep>/solo/src/minigrep.rs
use std::io;
pub fn run() {
let mut args: Vec<String> = Vec::new();
let mut age = String::new();
println!("What is your age?");
io::stdin().read_line(&mut age)
.expect("Failed to read line");
args.push(age);
println!("{:?}", &args[0]);
}<file_sep>/solo/src/lifetimes.rs
// lifetimes are specified with '
fn pr<'a> (x: &'a str, y: &'a str) -> &'a str {
if x.len() == y.len() {
x
} else {
y
}
}
pub fn run() {
let a = "a string";
let b = "b string";
// Static lifetimes live for program entirety
// Should avoid in most cases. Slows program
let s: &'static str = "The long lasting string";
let c = pr(a, b);
println!("{}", c);
}<file_sep>/solo/src/loops.rs
pub fn run () {
for_loops();
}
fn for_loops () {
let a = vec![10,20,30,40,50];
for i in a {
println!("i: {}", i);
}
// Exclusive ranges
// ..= -> Inclusive ranges (experimental)
for i in 1..11 {
println!("i: {}", i);
}
}
fn while_loops () {
let mut n = 10;
while n != 0 {
println!("{}!", n);
n = n - 1;
}
}
fn named_loops () {
'a: loop {
println!("loop a");
'b: loop {
println!("loop b");
'c: loop {
println!("loop c");
break 'b
}
}
continue
}
}
fn loop_value () {
let x = loop {
break 10;
};
println!("x: {}", x);
}<file_sep>/solo/src/vectors.rs
// Vecs
// Resizable Arrays
// Made up of three data points
// 1) Pointer to the data
// 2) length
// 3) Capacity
// Must have the same type
// Can use Enums to circumvent
use std::cmp::PartialOrd;
pub fn run () {
let mut numbers: Vec<i32> = vec![1,2,3,4,5];
numbers.push(6);
println!("Vec numbers = {:?}", numbers);
println!("Vec numbers occupies {} bytes", std::mem::size_of_val(&numbers));
// must use &(generic) before type [i32]
// equals whatever size the array is that is set to it
// &numbers[0(startINDEX)..5(numOfItems)]
let slice: &[i32] = &numbers[1..3];
println!("Slice of Vec numbers = {:?}", slice);
for vec in numbers.iter_mut() {
*vec *= 2;
}
println!("Vec numbers after iter_mut() {:?}", numbers);
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is {}", result);
// let largest = largest(&numbers);
// println!("Largest item in Vec = {}", largest);
}
#[derive(Debug)]
enum Example {
Float(f64),
Int(i32),
Text(String),
}
pub fn run_2 () {
let mut v: Vec<i32> = Vec::new();
for i in &v {
println!("{}", i);
}
println!("{:?} {} {}", &v, v.len(), v.capacity());
println!("{:?}", v.pop());
let r = vec![
Example::Int(142),
Example::Float(12.32),
Example::Text(String::from("string")),
];
println!("{:?}", &r);
}
pub fn largest <T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list.iter() {
if &item > &largest {
largest = &item;
}
}
&largest
}
pub fn make_vecs() {
println!("-- Making Vecs");
let mut v = Vec::new();
v.push("some value");
v.push("another value");
let mut v2 = vec![1,2,3];
v2.push(4);
println!("v = {:?} and v2 = {:?}", &v, &v2);
}
<file_sep>/apts_api/src/lib.rs
pub mod examples;
<file_sep>/solo/src/helpful_funcs.rs
pub fn run () {
}
fn count(v: &Vec<i32>, val: i32) -> usize {
v.into_iter().filter(|&&x| x == val).count()
}
fn copy<T>(t: T) -> T
where // Guard
T: Copy, // T must ba able to implement Trait Copy
{
let x = t;
x
}<file_sep>/apts_api/src/main_tst.rs
#[macro_use]
extern crate diesel;
// #[macro_use]
// extern crate diesel_codegen;
extern crate dotenv;
// use dotenv;
use std::env;
mod schema;
mod models;
fn main() {
// check to see if dotenv file
dotenv::dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("set DATABASE_URL");
let conn = PgConnection::establish(&database_url).unwrap();
let book = models::NewBook {
title: String::from("Gravity's Rainbow"),
author: String::from("<NAME>"),
published: true,
};
if models::Book::insert(book, &conn) {
println!("success");
} else {
println!("failed");
}
}
<file_sep>/solo/src/arrays.rs
pub fn run () {
let mut numbers: [i32; 5] = [1,2,3,4,5];
println!("numbers array = {:?}", numbers);
println!("numbers occupies {} bytes", std::mem::size_of_val(&numbers));
numbers[2] = 20;
// must use & (generic) before type [i32]
// equals whatever size the array is that is set to it
// &numbers[0(startINDEX)..5(numOfItems)]
let slice: &[i32] = &numbers[0..5];
println!("Slice of numbers = {:?}", slice);
}<file_sep>/solo/src/print.rs
pub fn run() {
println!(
"{name} likes to play {activity}",
name = "Charles",
activity = "lax"
);
println!(
"Binary: {0:b} Hex: {0:x} Octal: {0:o}", 11
);
println!("{:?}", (12, true, "hello"));
}<file_sep>/solo/src/conditionals.rs
use std::io;
pub fn run () {
loop {
// Get string from input
let mut age = String::new();
let check_id: bool = true;
let mut error: bool = false;
println!("What is your age?");
io::stdin().read_line(&mut age)
.expect("Failed to read line");
let age: u8 = match age.trim().parse() {
Ok(num) => num,
Err(_) => { error = true; 0 },
};
if error {
println!("There was an error");
continue;
}
else {
println!("The age you entered is {}", age);
break;
}
}
}<file_sep>/apts_api/Cargo.toml
[package]
name = "apts_api"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
mysql = "*"
# Powerful date and time functionality
chrono = { version = "0.4.6", features = ["serde"] }
# For connecting with the MySQL database
# diesel = { version = "1.4.2", features = ["chrono"] }
# diesel_codegen = { version = "0.16.1", features = ["mysql"] }
# dotenv = "*"
# Lazy static initialization
lazy_static = "1.3.0"
# Rocket Webserver
# rocket = "0.4.2"
# rocket_contrib = { version = "0.4.0", features = ["json", "diesel_mysql_pool"] }
# rocket_codegen = "*"
rocket = "0.4.2"
rocket_codegen = "*"
rand = "*"
[dependencies.rocket_contrib]
version = "*" # "0.4.0-rc.2" # or use *
default-features = false
features = ["handlebars_templates", "tera_templates"]
# Serialization/Deserialization
# serde_json = "1.0.39"
# serde = "1.0.90"
# serde_derive = "1.0.90" | 9e963f9a3d19f85c4be498382eee1c13992c8bdd | [
"TOML",
"Rust",
"SQL"
] | 25 | Rust | crollax/Rust | acc0911836e3ae9abde6a67a951e8140f63fe810 | 1e4c822ad448f2106331e6c5a05379d8c15f20b9 | |
refs/heads/master | <repo_name>trinh1999/MISA.AMIS_KeToan.TTSOnline.DT_Trinh<file_sep>/TTSOnline_DT.Trinh/FrontEnd/Misa.Amis.Vue/misa-amis-vuejs/src/js/common/common.js
import message from './message'
import $ from 'jquery'
import dayjs from "dayjs";
const common = {
/**
* Hủy hoặc thoát form dialog ==> tool-tip không hiện
* CreatedBy: DT.Trinh 30/8/2021
*/
turnOffValidate() {
console.log($('.input-item input[type=text]'));
var arrayInputText = $('.input-item input[type=text]');
for (let i = 0; i < arrayInputText.length; i++) {
arrayInputText[i].style.border = "";
arrayInputText[i].nextElementSibling.style.display = "none";
}
var arrayInputEmail = $('.input-item input[type=email]');
for (let i = 0; i < arrayInputEmail.length; i++) {
arrayInputEmail[i].style.border = "";
arrayInputEmail[i].nextElementSibling.style.display = "none";
}
},
/**
* check validate dữ liệu nếu dữ liệu không đúng
* @param {*} input các elements input
* @param {*} value key được đặt trên các thẻ input (ref)
* @param {*} message thông báo lỗi cho người dùng biết
* CreatedBy: DT.Trinh 30/8/2021
*/
turnOnValidate(input, value, message) {
input.style.border = "1px solid #F65454";
input.nextElementSibling.style.display = "block";
input.nextElementSibling.innerText = message;
$(input).attr('validate', false);
input.setAttribute('validate', false);
},
/**
* validate dữ liệu
* @param {*} input các element input có chứa ref
* @param {*} value dữ liệu của ref được gán trên thẻ input
* @returns true - đã check validate và dữ liệu đúng hết, false - dữ liệu đang sai
* createdBy: DT.Trinh 30/8/2021
*/
isValidateInput(input, value) {
// check bắt buộc nhập
if (value == '') {
common.turnOnValidate(input, value, message.VALIDATE_MSG_NO_SUCCESS);
return false;
}
},
isFormatInput(input, value){
var propName = input.getAttribute('prop-name');
if (propName == "Email") {
if (!common.isEmail(value)) {
common.turnOnValidate(input, value, message.VALIDATE_FORMAT_MSG_NO_SUCCESS);
return false;
}
}
if (propName == "IdentityNumber") {
if (!common.isIdentityNumber(value)) {
common.turnOnValidate(input, value, message.VALIDATE_FORMAT_MSG_NO_SUCCESS);
return false;
}
}
},
/**
* Định dạng cho email
* CreateBy DT.Trinh
*/
isEmail(email) {
//eslint-disable-next-line
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!regex.test(email)) {
return false;
} else {
return true;
}
},
/**
* Định dạnh CMND
* CreateBy DT.Trinh
*/
isIdentityNumber(cmt) {
//eslint-disable-next-line
var regex = /^([0-9]{9}|[0-9]{12})+$/;
if (!regex.test(cmt)) {
return false;
} else {
return true;
}
},
/**
* Hàm format date thàng dạng yyyy-mm-dd
* CreateBy DT.Trinh
*/
formatDateYMD(date) {
if (date == null) {
return new Date(date);
}
return dayjs(date).format("YYYY-MM-DD");
},
}
export default common;<file_sep>/TTSOnline_DT.Trinh/BackEnd/MISA.AMIS/MISA.ApplicationCore/Interfaces/Services/IEmployeeService.cs
using MISA.ApplicationCore.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.ApplicationCore.Interfaces.Services
{
public interface IEmployeeService: IBaseService<Employee>
{
#region METHOD
/// <summary>
/// Tạo mã mới
/// </summary>
/// <returns>Mã nhân viên mới</returns>
///CreateBy: DT.Trinh
string GetNewEmployeeCode();
/// <summary>
/// Tìm kiếm
/// </summary>
/// <param name="filter">Object chứa nội dung lọc</param>
/// <returns>Danh sách khách hàng theo đk</returns>
/// Created By : DT.Trinh
public Paging<Employee> GetEmployeesByPaging(EmployeeFilter filter);
#endregion
}
}
<file_sep>/TTSOnline_DT.Trinh/BackEnd/MISA.AMIS/MISA.ApplicationCore/Interfaces/Repository/IEmployeeRepository.cs
using MISA.ApplicationCore.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.ApplicationCore.Interfaces.Repository
{
public interface IEmployeeRepository: IBaseRepository<Employee>
{
/// <summary>
/// Lấy mã mới
/// </summary>
/// <returns></returns>
/// CreateBy: DT.Trinh
string GetNewEmployeeCode();
/// <summary>
/// Tìm kiếm
/// </summary>
/// <param name="filter">Object chứa nội dung lọc</param>
/// <returns>Danh sách khách hàng theo điều kiện lọc</returns>
/// Created By : DT.Trinh
public Paging<Employee> GetEmployeesByPaging(EmployeeFilter filter);
}
}
<file_sep>/TTSOnline_DT.Trinh/BackEnd/MISA.AMIS/MISA.ApplicationCore/Entities/EmployeeFilter.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MISA.ApplicationCore.Entities
{
public class EmployeeFilter
{
/// <summary>
/// Trang hiện tại
/// Created By : DT.Trinh
/// </summary>
public int PageIndex { get; set; } = 1;
/// <summary>
/// Số lượng bản ghi có trong 1 trang
/// Created By : DT.Trinh
/// </summary>
public int PageSize { get; set; } = 10;
/// <summary>
/// Lọc theo Mã NV / SĐT / HọTen
/// Created By : DT.Trinh
/// </summary>
public string KeySearch { get; set; } = "";
}
}
<file_sep>/TTSOnline_DT.Trinh/BackEnd/MISA.AMIS/MISA.Infrastructure/Repository/BaseRepository.cs
using Dapper;
using Microsoft.Extensions.Configuration;
using MISA.ApplicationCore.Entities;
using MISA.ApplicationCore.Interfaces.Repository;
using MISA.ApplicationCore.MISAAttribute;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MISA.Infrastructor.Repository
{
public class BaseRepository<TEntity> : IBaseRepository<TEntity>, IDisposable where TEntity : BaseEntity
{
//Truy cập vào database
//1. Khởi tạo thông tin kết nối database
#region DECLARE
/// <summary>
/// Kết nối tới DB
/// </summary>
protected IDbConnection _dbConnection;
/// <summary>
/// Thông tin kết nối
/// </summary>
public readonly string _connectionString;
/// <summary>
/// Tên bảng
/// </summary>
protected string _tableName;
#endregion
#region Contructor
public BaseRepository(IConfiguration configuration)
{
_tableName = typeof(TEntity).Name;
_connectionString = configuration.GetConnectionString("AmisDatabase");
}
#endregion
/// <summary>
/// Thêm bản ghi
/// </summary>
/// <param name="entity">Bản ghi cần thêm</param>
/// <returns>Trả về số bản ghi được thêm</returns>
/// CreateBy: DT.Trinh
public int Add(TEntity entity)
{
var rowEffects = 0;
_dbConnection = new MySqlConnection(_connectionString);
_dbConnection.Open();
using (var transaction = _dbConnection.BeginTransaction())
{
try
{
var parameters = MappingDbType(entity);
rowEffects = _dbConnection.Execute($"Proc_Insert{_tableName}", param: parameters, commandType: CommandType.StoredProcedure, transaction: transaction);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
return rowEffects;
}
/// <summary>
/// Xóa bản ghi
/// </summary>
/// <param name="entityId">Bản ghi cần xóa</param>
/// <returns>Số bản ghi đã xóa</returns>
/// CreateBy: DT.Trinh
public int Delete(Guid entityId)
{
_dbConnection = new MySqlConnection(_connectionString);
_dbConnection.Open();
var rowEffects = 0;
using (var transaction = _dbConnection.BeginTransaction())
{
try
{
var parameters = new DynamicParameters();
parameters.Add($"@{_tableName}Id", entityId);
rowEffects = _dbConnection.Execute($"Proc_Delete{_tableName}ById", param: parameters, commandType: CommandType.StoredProcedure, transaction: transaction);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
return rowEffects;
}
/// <summary>
/// Hàm get ra danh sách
/// </summary>
/// <returns>List danh sách</returns>
/// CreateBy: DT.Trinh
public IEnumerable<TEntity> Get()
{
_dbConnection = new MySqlConnection(_connectionString);
_dbConnection.Open();
var sql = $"Proc_Get{_tableName}s";
var entities = _dbConnection.Query<TEntity>(sql, commandType: CommandType.StoredProcedure);
return entities;
}
/// <summary>
/// Lọc bản ghi theo tên thuộc tính và giá trị thuộc tính
/// </summary>
/// <param name="entity">object</param>
/// <param name="property">Tên thuộc tính</param>
/// <returns></returns>
/// CreateBy: DT.Trinh
public TEntity GetByProp(TEntity entity, PropertyInfo property)
{
_dbConnection = new MySqlConnection(_connectionString);
_dbConnection.Open();
var propName = property.Name;
var keyValue = entity.GetType().GetProperty($"{_tableName}Id").GetValue(entity);
var propValue = entity.GetType().GetProperty(propName).GetValue(entity);
var query = string.Empty;
if (entity.EntityState == EntityState.AddNew)
{
query = $"SELECT * FROM {_tableName} WHERE {propName} = '{propValue}'";
}
else if (entity.EntityState == EntityState.Update)
{
query = $"SELECT * FROM {_tableName} WHERE {propName} = '{propValue}' AND {_tableName}Id <> '{keyValue}'";
}
else
{
return null;
}
var res = _dbConnection.QueryFirstOrDefault<TEntity>(query, commandType: CommandType.Text);
return res;
}
/// <summary>
/// Lọc theo id bản ghi
/// </summary>
/// <param name="entityId">id bản ghi</param>
/// <returns></returns>
/// CreateBy: DT.Trinh
public TEntity GetById(Guid entityId)
{
_dbConnection = new MySqlConnection(_connectionString);
_dbConnection.Open();
var parameters = new DynamicParameters();
parameters.Add($"@{_tableName}Id", entityId);
var res = _dbConnection.Query<TEntity>($"Proc_Get{_tableName}ById", param: parameters, commandType: CommandType.StoredProcedure).FirstOrDefault();
return res;
}
/// <summary>
/// Cập nhật bản ghi
/// </summary>
/// <param name="entity"></param>
/// <param name="entityId"></param>
/// <returns></returns>
/// CreatedBy: DT.Trinh
public int Update(TEntity entity, Guid entityId)
{
var rowEffects = 0;
_dbConnection = new MySqlConnection(_connectionString);
_dbConnection.Open();
using (var transaction = _dbConnection.BeginTransaction())
{
try
{
var parameters = MappingDbType(entity);
rowEffects = _dbConnection.Execute($"Proc_Update{_tableName}", param: parameters, commandType: CommandType.StoredProcedure, transaction: transaction);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
return rowEffects;
}
/// <summary>
/// Map dữ liệu của 1 entity sang thành dynamic parameters dùng cho truy vấn SQL
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="entity"></param>
/// <returns>dynamic parameters đã được format đúng</returns>
/// CreatedBy: DT.Trinh
protected DynamicParameters MappingDbType(TEntity entity)
{
var properties = entity.GetType().GetProperties();
var parameters = new DynamicParameters();
foreach (var property in properties)
{
var propertyName = property.Name;
var propertyValue = property.GetValue(entity);
var propertyType = property.PropertyType;
if (propertyType == typeof(Guid) || propertyType == typeof(Guid?))
{
parameters.Add($"@{propertyName}", propertyValue, DbType.String);
}
else
{
parameters.Add($"@{propertyName}", propertyValue);
}
}
return parameters;
}
/// <summary>
/// Close kết nối
/// </summary>
/// CreateBy: DT.Trinh
public void Dispose()
{
if (_dbConnection != null && _dbConnection.State == ConnectionState.Open)
{
_dbConnection.Close();
_dbConnection.Dispose();
}
}
}
}
<file_sep>/TTSOnline_DT.Trinh/FrontEnd/Misa.Amis.Vue/misa-amis-vuejs/src/js/common/message.js
const meassage = {
REFRESH_MSG_SUCCESS: "Bảng được tải lại thành công!",
//khi ấn nút xóa nhiều mà chưa chọn bản ghi để xóa
WARNING_MSG_DELETE_NO_SELECT_ROW: "Mời chọn bản ghi cần xóa!",
//Thêm nhân viên thành công
ADD_MSG_SUCCESS: "Thêm nhân viên thành công!",
//Thêm hoặc cập nhật không thành công
ADD_UPDATE_MSG_NO_SUCCESS: "Dữ liệu không hợp lệ! Vui lòng xem lại thông tin đã nhập",
//Sửa thông tin thành công
EDIT_MSG_SUCCESS: "Sửa thông tin thành công!",
//Thông báo 1 trường nào dấy bắt buộc nhập
VALIDATE_MSG_NO_SUCCESS: "Thông tin này không được để trống!",
//Thông báo yêu cầu nhập đủ trường thông tin bắt buộc
VALIDATE_MSG_MIS_REQUIRED: "Nhập thiếu trường thông tin bắt buộc hoặc thông tin chưa đúng định dạng!",
//Thông báo sai định dạng
VALIDATE_FORMAT_MSG_NO_SUCCESS: "Thông tin đã sai định dạng!",
//Xóa nhân viên thành công
DELETE_MSG_SUCCESS: "Xóa bản ghi thành công!",
//Exception message
EXCEPTION_MSG: "Có lỗi xảy ra! Vui lòng liên hệ với MISA",
}
export default meassage; | 52d8794d15a97ba6a2e5ad1bfa4d29cf870ec93a | [
"JavaScript",
"C#"
] | 6 | JavaScript | trinh1999/MISA.AMIS_KeToan.TTSOnline.DT_Trinh | f8ffab5f42ee3491e50424eb3feec8cf417081cf | 7a973329edcfa97abca7ef2717ee95662a48e16e | |
refs/heads/master | <repo_name>inowas/gwflowjs<file_sep>/src/helpers/index.js
import erf from './erf.js';
import erfc from './erfc.js';
import numericallyIntegrate from './numericallyIntegrate';
export {
erf,
erfc,
numericallyIntegrate
};
<file_sep>/src/gwMounding/mounding.js
import { erf, numericallyIntegrate } from '../helpers/index';
function S(alpha, beta) {
const func = (tau) => {
if (tau !== 0) {
const sqrtTau = Math.sqrt(tau);
return erf(alpha / sqrtTau) * erf(beta / sqrtTau);
}
return 0;
};
return numericallyIntegrate(0, 1, 0.001, func);
}
export function calculateHi(x, y, w, L, W, hi, Sy, K, t) {
const a = W / 2;
const l = L / 2;
const v = K * hi / Sy;
const sqrt4vt = Math.sqrt(4 * v * t);
const s1 = S((l + x) / sqrt4vt, (a + y) / sqrt4vt);
const s2 = S((l + x) / sqrt4vt, (a - y) / sqrt4vt);
const s3 = S((l - x) / sqrt4vt, (a + y) / sqrt4vt);
const s4 = S((l - x) / sqrt4vt, (a - y) / sqrt4vt);
return Math.sqrt(w / 2 / K * v * t * (s1 + s2 + s3 + s4) + hi * hi).toFixed(5) - hi.toFixed(5); // eq 1
}
export function calculateHMax(w, L, W, hi, Sy, K, t) {
return calculateHi(0, 0, w, L, W, hi, Sy, K, t) + hi;
}
<file_sep>/src/transport1d/index.js
import * as transport1d from 'transport1d';
export { transport1d };
<file_sep>/src/helpers/numericallyIntegrate.js
export default function numericallyIntegrate( a, b, dx, f ) {
// define the variable for area
let area = 0;
// loop to calculate the area of each trapezoid and sum.
for ( let x1 = a + dx; x1 <= b; x1 += dx ) {
// the x locations of the left and right side of each trapezoid
const x0 = x1 - dx;
// the area of each trapezoid
const Ai = dx * ( f( x0 ) + f( x1 ) ) / 2.0;
// cumulatively sum the areas
area += Ai;
}
return area;
}
<file_sep>/README.md
# INOWAS Groundwater-Flow-Library [![Build Status](https://img.shields.io/travis/inowas/gwflowjs/master.svg)](https://travis-ci.org/inowas/gwflowjs)
A set of analytical functions to calculate different kind of groundwater-flow processes.
## Documentation
- [1D transport model (Ogata-Banks)](https://wiki.inowas.hydro.tu-dresden.de/t08-1d-transport-model-ogata-banks/)
- [Groundwater mounding (Hantush)](https://wiki.inowas.hydro.tu-dresden.de/t02-groundwater-mounding-hantush/)
## Contribute
### Clone repository
git clone https://github.com/inowas/gwflowjs.git
### Install dependencies
yarn install
### Run Tests
yarn test
<file_sep>/test/transport1D.spec.js
/* global describe, it, before */
import chai from 'chai';
import {transport1d} from '../src/index';
chai.expect();
const expect = chai.expect;
describe('Given the transport1d-function (ogata-banks)', () => {
const values = [
[725, 15, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 0.02313],
[500, 15, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 0.02313],
[500, 13, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 0.07249],
[500, 10, 13650, 2.592, 0.002, 0.23, 0.923, 0.01, 1.0000]
];
values.forEach(v => {
const decimals = 5;
const C0 = v[0];
const x = v[1];
const t = v[2];
const K = v[3];
const I = v[4];
const ne = v[5];
const alphaL = v[6];
const Kd = v[7];
const expected = v[8].toFixed(decimals);
it('calculating transport1d-function should return ' + expected, () => {
expect(transport1d.calculateC(x, t, K, I, ne, alphaL, Kd).toFixed(decimals)).to.be.equal(expected);
});
});
});
describe('Given the transport1d-function (ogata-banks)', () => {
const values = [
[725, 15, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 2500],
[500, 15, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 2500],
[500, 13, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 420],
[500, 13, 365, 40, 0.002, 0.23, 0.923, 0.01, 60],
[500, 10, 13650, 2.592, 0.002, 0.23, 0.923, 0.01, 180]
];
values.forEach(v => {
const decimals = 5;
const C0 = v[0];
const x = v[1];
const t = v[2];
const K = v[3];
const I = v[4];
const ne = v[5];
const alphaL = v[6];
const Kd = v[7];
const expected = v[8].toFixed(decimals);
it('calculating Tmax-function should return ' + expected, () => {
expect(transport1d.calculateTmax(x, K, I, ne, alphaL, Kd).toFixed(decimals)).to.be.equal(expected);
});
});
});
describe('Given the transport1d-function (ogata-banks)', () => {
const values = [
[725, 15, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 20],
[500, 15, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 20],
[500, 13, 365, 2.592, 0.002, 0.23, 0.923, 0.01, 20],
[500, 13, 365, 40, 0.002, 0.23, 0.923, 0.01, 200],
[500, 10, 13650, 2.592, 0.002, 0.23, 0.923, 0.01, 400]
];
values.forEach(v => {
const decimals = 5;
const C0 = v[0];
const x = v[1];
const t = v[2];
const K = v[3];
const I = v[4];
const ne = v[5];
const alphaL = v[6];
const Kd = v[7];
const expected = v[8].toFixed(decimals);
it('calculating XMax-function should return ' + expected, () => {
expect(transport1d.calculateXmax(t, K, I, ne, alphaL, Kd).toFixed(decimals)).to.be.equal(expected);
});
});
});
<file_sep>/src/helpers/erf.js
export default function erf(x, decimals = 7) {
const a1 = 0.254829592;
const a2 = -0.284496736;
const a3 = 1.421413741;
const a4 = -1.453152027;
const a5 = 1.061405429;
const p = 0.3275911;
// Save the sign of x
let sign = 1;
if (x < 0) sign = -1;
const absX = Math.abs(x);
// A & S 7.1.26 with Horners Method
const t = 1.0 / (1.0 + p * absX);
const y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.exp(-absX * absX);
return (sign * y).toFixed(decimals);
}
| e658ebbf55cbf058777913e49f760d76d32042da | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | inowas/gwflowjs | d86e2f1a16c42436ff0ffc34cb90d61b6bc79d0b | 7e975b1ff99ebd6f45e961eebffc69ff516e2155 | |
refs/heads/master | <repo_name>pesaman/abulita_sorda_rails<file_sep>/config/routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'home#home'
post '/abuelita' => 'home#abuelita'
get '/abuelita' => 'home#abuelita'
end
<file_sep>/app/controllers/home_controller.rb
class HomeController < ApplicationController
def home
@abuelita = params[:abuelita]
end
def abuelita
p "<>"* 100
p mesage1 = params[:mesage]
p "<>"* 100
saludo = mesage1
if saludo == nil
elsif saludo.downcase == "bye tqm bye tqm bye tqm"
@abuelita = "BYE TQM"
elsif saludo == saludo.upcase
@abuelita = "NO, NO DESDE 1983"
elsif saludo == saludo.downcase
@abuelita = "HUH?! NO TE ESCUCHO, HIJO!"
end
render ("home")
end
end
| 69f81ba504b8923262ce73de35f7fa4100d8c03d | [
"Ruby"
] | 2 | Ruby | pesaman/abulita_sorda_rails | 5f51db4ce1d7a8187efb1f6a7cd15fef4d11f0a6 | a31a42764679709047b4e02c201ce90c9a052478 | |
refs/heads/main | <repo_name>sasquatchchicken/the_first_instance<file_sep>/README.md
# the_first_instance
so I was tasked with creating a python fuction that would take in the user input and replace the
first instance of the first character in the string and all remaining occurrences with a *
<file_sep>/replace_first_instance.py
#!/usr/bin/env python3
s = input("please type in a string :\n")
position = s[0] #here I have set the index postion to zero this means we will be referencing the first char of
#the string given as input by the user.
replace_char = s[1:].replace(position, "*") #simple operation performing the task
#setting the new char as replace_char "*" and telling it to
#replace the first and all occurances of index [0] that is the
#first position of a charactor in a string .
print(position+replace_char)
| 58a18e83f2a104039955c5fc8a5ea98fd68601f8 | [
"Markdown",
"Python"
] | 2 | Markdown | sasquatchchicken/the_first_instance | 0fd2a6395e170132b13f1ef8e07bbc007c0bdd71 | b4b38051c3d8541bf06ccf8bd9d98c042a3be9dc | |
refs/heads/main | <file_sep>/*
* MIT License
*
* Copyright (c) 2020 <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 org.engineer365.platform.user.app.service;
import org.engineer365.platform.user.api.bean.Account;
import org.engineer365.platform.user.api.bean.User;
import org.engineer365.platform.user.api.req.AccountAuthReq;
import org.engineer365.platform.user.api.req.CreateAccountByEmailReq;
import org.engineer365.platform.user.api.req.CreateUserByEmailReq;
import org.engineer365.platform.user.app.entity.AccountEO;
import org.engineer365.platform.user.app.entity.UserEO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.engineer365.common.misc.UuidHelper;
import org.engineer365.platform.user.api.UserApiV1;
@Service
@lombok.Setter
@lombok.Getter
@Transactional(propagation = Propagation.REQUIRED)
public class UserApiV1Service implements UserApiV1 {
@Autowired
AccountService accountService;
@Autowired
UserService userService;
@Override
public Account getAccount(String accountId) {
var r = getAccountService().getAccount(false, accountId);
return AccountEO.OUTPUT_COPIER.copy(r);
}
@Override
public Account getAccountByEmail(String email) {
var r = getAccountService().getAccountByEmail(false, email);
return AccountEO.OUTPUT_COPIER.copy(r);
}
@Override
public User getUser(String userId) {
var r = getUserService().getUser(false, userId);
return UserEO.OUTPUT_COPIER.copy(r);
}
@Override
public String authByAccount(AccountAuthReq areq) {
return getAccountService().authByAccount(areq);
}
@Override
public Account createUserByEmail(CreateUserByEmailReq req) {
var aidAndUid = UuidHelper.shortUuid();
var ureq = CreateUserByEmailReq.USER_REQ_COPIER.copy(req);
ureq.setPrimaryAccountId(aidAndUid);
getUserService().createUser(aidAndUid, ureq);
var areq = CreateUserByEmailReq.ACCOUNT_REQ_COPIER.copy(req);
areq.setUserId(aidAndUid);
return _createAccountByEmail(areq, aidAndUid);
}
@Override
public Account createAccountByEmail(CreateAccountByEmailReq req) {
var aid = UuidHelper.shortUuid();
return _createAccountByEmail(req, aid);
}
Account _createAccountByEmail(CreateAccountByEmailReq req, String accountId) {
var u = getUserService().getUser(true, req.getUserId());
var a = getAccountService().createAccountByEmail(accountId, req, u);
return AccountEO.OUTPUT_COPIER.copy(a);
}
}
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 engineer365.org
*
* 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 org.engineer365.common;
import java.util.Set;
import org.engineer365.common.error.ForbiddenError;
import org.engineer365.common.misc.StringHelper;
import org.engineer365.common.security.Role;
import org.engineer365.common.bean.Dumpable;
/**
* 当前API请求的上下文(主要是用户和权限等)
*/
@lombok.Getter
@lombok.Setter
public class RequestContext extends Dumpable {
static final ThreadLocal<RequestContext> CURRENT = new ThreadLocal<>();
String userId;
Set<Role> roles;
public static RequestContext bind(RequestContext ctx) {
var old = current();
CURRENT.set(ctx);
LogTrace.setContext(ctx);
return old;
}
public static RequestContext copy(RequestContext that) {
var r = new RequestContext();
if (that != null) {
r.setUserId(that.getUserId());
r.setRoles(that.getRoles());
}
return r;
}
public static void clear() {
LogTrace.clear();
CURRENT.remove();
}
public static RequestContext current() {
return CURRENT.get();
}
public static RequestContext load(boolean ensureHasUserId) {
var r = current();
if (r == null) {
throw new ForbiddenError(ForbiddenError.Code.CONTEXT_NOT_FOUND);
}
if (ensureHasUserId && StringHelper.isBlank(r.getUserId())) {
throw new ForbiddenError(ForbiddenError.Code.USER_ID_NOT_FOUND_IN_CONTEXT);
}
return r;
}
}
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 engineer<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 org.engineer365.platform.user.app.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.engineer365.platform.user.api.bean.Account;
import org.engineer365.platform.user.api.enums.AccountType;
import org.engineer365.platform.user.api.req.CreateAccountByEmailReq;
import org.engineer365.common.bean.BeanCopyer;
import org.engineer365.common.entity.UpdateableEO;
@lombok.Getter
@lombok.Setter
@lombok.NoArgsConstructor
@Entity
@Table(name = "user_account")
public class AccountEO extends UpdateableEO {
public static final BeanCopyer<AccountEO, Account> OUTPUT_COPIER = new BeanCopyer<AccountEO, Account>(
AccountEO.class, Account.class, Account::new, Account[]::new) {
@Override
protected void doRender(AccountEO source, Account target) {
super.doRender(source, target);
var u = source.getUser();
if (u != null) {
target.setUserId(u.getId());
}
}
};
public static final BeanCopyer<CreateAccountByEmailReq, AccountEO> CREATE_BY_EMAIL_REQ_COPIER
= new BeanCopyer<CreateAccountByEmailReq, AccountEO>(
CreateAccountByEmailReq.class, AccountEO.class, AccountEO::new, AccountEO[]::new) {
@Override
protected void doRender(CreateAccountByEmailReq source, AccountEO target) {
super.doRender(source, target);
target.setType(AccountType.EMAIL);
target.setCredential(source.getEmail());
}
};
@ManyToOne(optional = false)
@JoinColumn(name = "user_id", nullable = false)
UserEO user;
@Enumerated(EnumType.STRING)
@Column(length = 16, name = "type", nullable = false)
AccountType type;
@Column(length = 64, name = "credential", nullable = false)
String credential;
@Column(name = "password", length = 64, nullable = false)
String password;
}
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 engineer<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 org.engineer365.common.service;
import org.engineer365.common.error.GenericError;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.mockito.ArgumentMatchers;
import org.mockito.MockitoAnnotations;
import org.opentest4j.AssertionFailedError;
import org.junit.jupiter.api.function.Executable;
import org.junit.jupiter.api.BeforeEach;
/**
*/
@Disabled
public abstract class ServiceTestBase {
@BeforeEach
public void beforeEach() {
MockitoAnnotations.openMocks(this);
}
public static boolean matchBoolean(boolean that) {
return ArgumentMatchers.booleanThat(b -> {
Assertions.assertEquals(Boolean.valueOf(that), b);
return true;
});
}
public static String matchString(String that) {
return ArgumentMatchers.argThat((String actual) -> that.equals(actual));
}
public static int matchInt(int that) {
return ArgumentMatchers.intThat(i -> {
Assertions.assertEquals(Integer.valueOf(that), i);
return true;
});
}
@SuppressWarnings("unchecked")
public static <T extends GenericError> T assertThrows (Class<T> expectedType, Enum<?> code, Executable executable) {
try {
executable.execute();
} catch (Throwable actualException) {
if (expectedType.isInstance(actualException)) {
return (T) actualException;
}
// UnrecoverableExceptions.rethrowIfUnrecoverable(actualException);
throw new AssertionFailedError("caught unexpected exception", expectedType, actualException.getClass(), actualException);
}
throw new AssertionFailedError("no expected exception throw", expectedType, "null");
}
}
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 <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 org.engineer365.common.json;
import com.fasterxml.jackson.core.type.TypeReference;
/**
* Json工具类
*/
public class JSON {
public static final ThreadLocal<JacksonHelper> MAPPER
= ThreadLocal.withInitial(() -> new JacksonHelper(JacksonHelper.buildMapper()));
/** 序列化成易读格式的JSON字符串 */
public static String pretty(Object object) {
return to(object, true);
}
/** 序列化成压缩格式的JSON字符串 */
public static String to(Object object) {
return to(object, false);
}
/**
* 序列化成指定格式的JSON字符串
*
* @param object 待序列化成JSON字符串的对象
* @param pretty true表示转成易读格式,否则转成压缩格式
*/
public static String to(Object object, boolean pretty) {
return MAPPER.get().to(object, pretty);
}
/**
* 把JSON反序列化成指定类型的对象
*
* @param text JSON字符串
* @param clazz 指定类型
*/
public static <T> T from(String json, Class<T> clazz) {
return MAPPER.get().from(json, clazz);
}
/**
* 把JSON反序列化成指定类型引用的对象,通常用于generic对象
*
* @param text JSON字符串
* @param clazz 指定类型引用
*/
public static <T> T from(String json, TypeReference<T> typeReference) {
return MAPPER.get().from(json, typeReference);
}
}
<file_sep>--
-- MIT License
--
-- Copyright (c) 2020 <EMAIL>3<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.
-- 用户模块的MySQL数据库初始化SQL
SET FOREIGN_KEY_CHECKS=0;
-- DROP TABLE IF EXISTS `user_account`;
CREATE TABLE `user_account` (
`id` CHAR(22) CHARACTER SET latin1 NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`version` INT NOT NULL,
`modified_at` DATETIME(3) NOT NULL,
`user_id` CHAR(22) CHARACTER SET latin1 NOT NULL,
`type` VARCHAR(16) CHARACTER SET latin1 NOT NULL,
`credential` VARCHAR(64) NOT NULL,
`password` VARCHAR(64) CHARACTER SET latin1 NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB, DEFAULT CHARACTER SET utf8mb4;
CREATE INDEX `idx_user_account_user_id` ON `user_account`(`user_id`(8));
CREATE UNIQUE INDEX `idx_user_account_biz_key` ON `user_account`(`credential`, `type`);
-- DROP TABLE IF EXISTS `user_user`;
CREATE TABLE `user_user` (
`id` CHAR(22) CHARACTER SET latin1 NOT NULL,
`created_at` DATETIME(3) NOT NULL,
`version` INT NOT NULL,
`modified_at` DATETIME(3) NOT NULL,
`name` VARCHAR(32) NOT NULL,
`full_name` VARCHAR(64) NOT NULL,
`primary_account_id` CHAR(22),
`is_root` BOOLEAN DEFAULT FALSE NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB, DEFAULT CHARACTER SET utf8mb4;
CREATE UNIQUE INDEX `idx_user_user_name` ON `user_user`(`name`);
<file_sep>#!/bin/bash
#
# MIT License
#
# Copyright (c) 2020 <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.
set -e
work_dir=$dev_dir/work
mysql_dir=$work_dir/mysql
# 'Darwin' or 'Linux'
export OS=`uname -s`
case "$OS" in
"Darwin" )
_sudo=''
;;
"Linux" )
_sudo='sudo'
# sudo chown -R $USER:$USER $data_dir
;;
* )
echo "Support MAC-OS-X or Linux only"
exit 1
;;
esac
# print the environment
echo ''
echo 'Work directory: ' $work_dir
echo 'MySQL data directory: ' $mysql_dir
echo ''
<file_sep># 一个示范性项目:云原生的微服务开发工程
(项目刚启动,组队中,欢迎加入)
## 两个出发点
- 示范完整的云原生的微服务架构
已有的开源项目,Spring Cloud系列貌似更多,云原生的微服务架构其实也是一个主流路线,会成为甚至已经成为下一代新的技术。种种原因,在国内的普及程度相对滞后,值得我们去做些什么。
- 整个开发过程以接近实际工程的方式展示出来,包括但不限于:持续集成、持续部署、自动化运维、多开发环境管理,等等
我做了调研,总结下来是,有的专注于某一技术点,有的专注于小范围内的整合,有的专注于完整的产品级代码,还有的专注于教学式的课程。代码和工程的系统结合目前我没看到,但价值的分量明显足够。
## 具体想法:
- 采用云原生的微服务架构: Docker, Kubernetes, ServiceMesh。
- 实现一个功能需求上能覆盖计划的技术栈的Web应用,目前考虑是一个二手计算机图书电商系统,注意,是<b>真的准备让大家的书上架的</b>!
- 前后端分离,以后端为主,后端最初会以JAVA的Spring Boot全家桶开始,包括MySQL、Redis、RabbitMQ、ElasticSearch等基本的主流技术栈,然后一步步增加别的,包括支持GO等其他语言;前端最初用React或Vue的全家桶开发SPA Web应用,然后扩展到小程序和手机App,逐步建立大前端体系。
- 自动化测试:单元测试、集成测试、性能测试、压力测试、端对端功能测试。整体测试覆盖率达到100%。
- 以DevOps和GitOps为理念的工程开发体系:
- 持续集成(CI),持续部署(CD)
- 自动化运维、自动化监控报警、集中式日志、分布式调用链路追踪
- 部署私有仓库
- 整合常见开发工具,譬如SonarQube, Slack,GITHUB Issue、GITHUB Project等。
- 建立示范性的本机开发环境、测试环境、预生产环境和线上生产环境
- 所使用的每一项技术都建立指南文档。
- 后续会加入大数据分析。
- 考虑演进成Serverless/FaaS,目前还没定,也可能会是另一个新项目。
## 如何报名参加?
这个项目是开放的,开源项目理论上没有门槛,谁想参加都可以,PR是最硬核的对参与程度的衡量,PR一合并会自动记入贡献者名单。
我已经根据一期开发的目标动手在写代码了。我相信大家肯定是很感兴趣的,但必然有很多人会因为时间精力等各种原因还没法直接参与开发。其实做贡献的方式有很多种,不是只有PR才算是参与了,很欢迎大家能提出建议、提出需求、帮助测试提BUG、帮助写文档,等等。所以,只要你有一定兴趣,那么:
1. 请Fork这个项目,把你的GITHUB账号名加到[./members.md](./members.md)那个文件,然后提交PR,等待合并。
2. Watch这个项目,任何项目变动都能得到邮件通知。
3. PR合并成功后,加入QQ群1033056382(目前不打算用微信)。加群时需要回答你提交PR时用的GITHUB账号。
4. 入群后,请把你的群内昵称改为GITHUB账号名,否则会被踢出。
5. 可选:Star一下,有助于我们找到更多参与者
对这个过程如果有什么问题,可以提交Issue [https://github.com/engineer-365/cloud-native-micro-service-engineering/issues]
## 目标:
(欢迎补充等建议)
- 一期开发:
- 阶段性目标:
- 最小化功能实现,前后端打通,但只实现书店顾客前端,不做管理员后端
- 模块化的单体应用
- 手动部署,直接上线运行
- 阶段性技术栈:
- 后端 -> Java技术栈:
- [ ] Spring MVC: REST API(JSON), Swagger (Spring Fox)
- [ ] 测试: Junit5 (单元测试), Mockito (Mock), JaCoCo (测试覆盖率分析)
- [ ] 数据库访问:Spring Data JPA(Hibernate),QueryDSL(动态查询),Flyway(数据库升级管理)
- [ ] 日志:Logback
- [ ] Jar包依赖管理:Maven
- [ ] Spring Boot Actuator:监控数据采集和管理
- [ ] 其他:Guava(工具类),Lombok (Java Bean代码生成)
- 前端 -> React全家桶:
- [ ] Webpack
- [ ] 路由:React Router
- [ ] UI库:Material Design或Ant Design
- [ ] REST客户端:Axios
- [ ] 测试:Jest或Mocha
- [ ] Nginx做前端静态页面和后端API的统一入口
- [ ] 关系数据库:MySQL单节点,H2(测试用)
- [ ] 持续集成(CI):Jenkins, SonarQube (代码质量检查)
- [ ] Maven私有仓库:Nexus,或JFrog
- [ ] 私有Docker仓库:Habor
- [ ] 开发者本地Docker开发环境:Docker-compose
- [ ] 用Helm或Kustomize手动部署到Kubernetes
- [ ] Spring Boot Admin
<img src="./doc/phases/phase-1.png" alt="image"/>
- 二期开发:
- 阶段性目标:
- 主要功能全部实现,包括管理员前端
- 初步实现云原生的微服务架构
- 自动部署
- 阶段性技术栈
- 后端增加:
- [ ] 参数校验: javax.validation (JSR-303, Hibernate Validator)
- [ ] 测试: Cucumber, TestContainers (容器化测试),JMeter (性能测试和压测),Contract
- [ ] 权限控制:Spring Security (OAuth + JWT)
- [ ] 日志:JSON日志格式
- [ ] REST客户端: Resilience4J,Spring RestTemplate或Open Feign
- [ ] 缓存:Jedis, Spring Data Redis, Caffeine
- [ ] 全文检索:Spring Data Elasticsearch
- [ ] 消息队列:Spring AMQP, RabbitMQ
- [ ] 定时任务:TBD
- 前端增加:
- [ ] 状态管理:Redux或MobX
- [ ] 测试:Selenium,Puppeteer
- [ ] 关系数据库:高可用MySQL集群(MySQL Router + Group Replication + MySQL Shell)
- [ ] 持续部署(CD):Ranchor(Kubernetes集群管理),gitkube, ArgoCD(自动部署到Kubernetes)
- [ ] 分布式缓存:Redis, Redis Sentinel
- [ ] ELK (Elasticsearch + Logstash + Kibana): 全文检索,日志管理
- [ ] 配置集中管理:Consul,Vault(MySQL等密码管理),Git2Consul
- [ ] 分布式调用链路追踪:OpenTracing, Jaeger
- [ ] 监控报警:Prometheus,Grafana
- [ ] Skaffold
<img src="./doc/phases/phase-2.png" alt="image"/>
- 三期开发:
- 阶段性目标:
- 主要功能全部实现
- 完整实现云原生的微服务架构
- 支持多语言
- 云原生的持续集成、持续部署、自动化运维
- 阶段性技术栈
- 后端:
- [ ] 支持用GO,Python,Node.JS,PHP开发微服务
- [ ] 部分微服务改用Serverless/FaaS实现
- [ ] 部分微服务改用异步/WebFlux实现
- [ ] GraphQL API
- [ ] gRPC
- [ ] WebSocket
- [ ] Workflow
- 前端:
- [ ] GraphQL API
- [ ] snowplow
- [ ] API网关:Kong,Ambassador,Gloo或Traefix?
- [ ] ServiceMesh: lstio
- [ ] NoSQL数据库:MongoDB, Neo4J
- [ ] 自动化运维:Ansible,Vagrant,Terraform
- [ ] Jenkins-X
<img src="./doc/phases/phase-3.png" alt="image"/>
- 四期开发:
- 阶段性目标:
- 对接云供应商:阿里云,AWS,Azure等
- 大数据分析:Flink,Hive, Kafka, ClickHouse等
- 全面高可用
- 尝试更多新技术
- 手机App、微信小程序
- 阶段性技术栈
- GraalVM, Quarkus
- Flutter
- Crossplane
- chaos-mesh
- TiDB, PostgreSQL/Cockroachdb
<img src="./doc/phases/phase-4.png" alt="image"/>
## 问答:
> 1. "太多了,一看就跟不上,就连这个简介都看不懂"
首先,我的观点是:看得懂就不用一起学了。很多我也只是个大概的了解,一步一步来吧,让我们在实践中一起学习。现在的趋势就是云原生、微服务、DevOps,列出的这些技术是在跟着大趋势走,避免走弯路,避免重复发明轮子,希望走到主流的前排里。跟着教程书学效果不好,真正的技术只可能在系统化的实践中才学得到学得好。
然后,太多的技术点(实际上还只是一小部分)恰恰也是为什么要发起这个项目的原因之一:想示范如何系统的使用这些技术。列出这么多名词术语有些唬人,因为大部分其实是成熟公司里已经用起来的技术,但是对刚入门的程序员来说就是个门槛,会懵,用过了、过了这个门槛,会发现很多事情只是知道不知道的区别。
> 2. “为什么不是Spring Cloud?”
云原生是微服务架构的主流路线之一,特点是服务治理的实现需要代码修改量少甚至不需要修改,意味着代码侵入性小,多语言支持方便,扩展性强。
另一方面,Spring Cloud的优秀开源演示项目已经很多,相对来说云原生方案因为比较新,项目发展空间更大,而且,云原生架构对基础架构和工程规范化的要求更高,而演示基础架构和规范化的工程开发正是这个项目的主要目标之一,希望能通过这个项目为促进云原生方案的普及作出贡献。
另外,项目里会用到一些Spring Cloud体系内的组件,但总体来说,并不是Spring Cloud的方案。
> 3. “我不喜欢或者不习惯你提到的技术,我还想尝试一个更新的技术,能不能换成xx?”,譬如,有群友提到:“最近正好有计划做一个类似的,想做的平台是基于vertex的kotlin和actix的rust,以及尽量全套的异步组件,顺便试试postgresql。”
选择成熟的主流技术是刻意的,这个项目的主要目标不是调研和尝鲜,主要目标是让大家脱离教程和作坊式的开发,让大家有机会实践贴近真实的规范化的工程开发。涉及的方方面面的细节会很多很杂,所以,为了降低项目失败的可能性,至少在前两阶段的计划中,我刻意采取了保守的技术选择策略。
这和尝试更新的技术并不矛盾,在初期的迭代取得了阶段性成果以后,我们会得到一个很好的平台,我们会更有士气更有真实需求去实践更多的东西,甚至做些重复发明轮子的事情都可以。
所以,就拿上面这个问题提到的“异步/非阻塞”的这个话题来说,因为在典型的Java Web应用系统里异步还不是主流,所以虽然这个想法不错,可是不太适合初始阶段,后续肯定会尝试异步方案。
> 4. “一开始关注后端就好了,也不仅仅限制于前后端分离,需要的是提供如何将自己的前端技术栈接入该后端项目的接口规范和指南,像react,vue,或者后端渲染,或者模板引擎等等”
第一期计划里是安排了实现一个书店顾客的Web前端,因为定位是一个系统化的工程化的演示性项目,前后端一起联动着实践才能体现工程中一个接口的开发过程。
> 5. "可以提供一些项目额外的包,例如该项目叫awesome, 就可以提供awesome-react-starter, awesome-vue-starter, awesome-blazor-starter, 毕竟专注后端,在一个项目集成与前端相关的一些东西多少会有些不好"
是的,会产出一些框架性的胶水性的代码和工具,会控制在很薄的一层封装上,目的是减少重复代码,提高工程效率和架构细节上的的一致性。顺便强调一下,这个项目并不是专注后端,而是因为通常产品开发围绕着后端作为中心,所以目前重点演示以后端为主的完整产品开发工程。
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 <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 org.engineer365.platform.user.app.service;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.engineer365.platform.user.api.req.CreateUserReq;
import org.engineer365.platform.user.app.dao.UserDAO;
import org.engineer365.platform.user.app.entity.UserEO;
import org.engineer365.common.service.ServiceTestBase;
public class UserServiceTest extends ServiceTestBase {
@Mock
UserDAO dao;
@InjectMocks
UserService target;
@Test
void test_createAccount_happy() {
var userId = "u-1";
var req = new CreateUserReq();
req.setFullName("n-1");
when(this.dao.save(ArgumentMatchers.any())).thenReturn(new UserEO());
this.target.createUser(userId, req);
verify(this.dao).save(argThat((UserEO entity) -> {
Assertions.assertNotNull(entity.getId());
Assertions.assertEquals(req.getFullName(), entity.getFullName());
return true;
}));
}
}
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 <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 org.engineer365.platform.user.app.service;
import org.engineer365.common.error.BadRequestError;
import org.engineer365.platform.user.api.enums.ErrorCode;
import org.engineer365.platform.user.api.req.CreateUserReq;
import org.engineer365.platform.user.app.entity.UserEO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.engineer365.platform.user.app.dao.UserDAO;
@Service
@lombok.Setter
@lombok.Getter
public class UserService {
@Autowired
UserDAO dao;
public UserEO getUser(boolean ensureExists, String userId) {
return getDao().get(ensureExists, userId);
}
public UserEO getByName(String name) {
return getDao().getByName(name);
}
public UserEO createUser(String userId, CreateUserReq req) {
var d = getDao();
if (d.getByName(req.getName()) != null) {
throw new BadRequestError(ErrorCode.USER_NAME_DUPLICATES);
}
var r = UserEO.CREATE_REQ_COPIER.copy(req);
r.setId(userId);
return d.save(r);
}
}
<file_sep>开发记录:
2020-11-28:
- [./server_code_init.md](./server_code_init.md): 后端代码始化
<file_sep>## 后端代码初始化:
- 使用spring boot的官方工具: https://start.spring.io
这个是生成的记录:https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.0.RELEASE&packaging=jar&jvmVersion=11&groupId=org.engineer365&artifactId=fleashop&name=fleashop&description=Demo%20project%20for%20Spring%20Boot&packageName=org.engineer365.fleashop&dependencies=lombok,configuration-processor,web,data-jpa,flyway,h2,mysql,actuator
截图:[./server_code_init/start.spring.io.png](./init/start.spring.io.png)
start.spring.io生成的[./server_code_init/HELP.md](./server_code_init/HELP.md):<file_sep># 二手书店的服务器端
## 示范的技术
- Spring Boot:
- 官网:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/
- JaCoCo:
测试覆盖率工具
- 官方文档: https://www.jacoco.org/jacoco/trunk/doc/
- Flyway:
数据库初始化和升级管理
- 官网:https://flywaydb.org/
- QueryDSL:
替代JPA自身的Criteria API,和Criteria API一样支持灵活的动态数据库查询语句,但相比JPA Criteria API:
1. 通过插件把数据库表的表名和列名绑定到类型安全的Java Bean property,方便重构,也减少直接使用字符串时容易发生的拼写错误
2. 查询条件用DSL风格的级联方式表达,接近直接写SQL,简单直观,容易学习使用
- 官网:http://www.querydsl.com/
- 简介文章:https://www.baeldung.com/intro-to-querydsl
- 参考手册:http://www.querydsl.com/static/querydsl/latest/reference/html_single/
- H2:
仅用于单元测试。
- 用于单元测试的优点:
1. 快 - 对于单元测试这非常重要
2. 不需要数据清理 - 因为H2是内存数据库,默认设置下数据不放磁盘,因此简化了单元测试的准备工作
- Lombok:
代码生成插件,通过简单的annotation来消除一些常见的无聊的Java代码,譬如Getter和Setter。
- 官网:https://projectlombok.org
- 简介文章:
1. https://blog.csdn.net/ThinkWon/article/details/101392808
2. https://www.jianshu.com/p/365ea41b3573
注意:IDE里使用需要安装和该IDE集成的插件,否则IDE会不会触发代码生成、找不到生成的代码而报编译错误。
常见的IDE插件:
1. VS Code:https://marketplace.visualstudio.com/items?itemName=GabrielBB.vscode-lombok
2. IDEA:待补充
3. Eclipse:待补充
## 本地构建
- 编译打包:
```./mvnw package```
第一次构建会从maven官网下载依赖到的很多第三方包,会很慢,最好是开着梯子。
后续会搭建自己的代理/镜像服务器,因为代理/镜像服务器也是实际工程(国内)的一部分
- 可选:下载第三方包的源代码和javadoc,方便调试和学习
```mvn dependency:sources```
```mvn dependency:resolve -Dclassifier=javadoc```
- 启动/查看log/停止
- Mac或Linux
- ```dev/up.sh```
- ```dev/log.sh```
- ```dev/down.sh```
- Windows
- TODO:bat脚本待写,以下命令待验证
```shell
cd dev
docker-compose up --build -d --remove-orphans
```
```shell
cd dev
docker-compose logs
```
```shell
cd dev
docker-compose down --remove-orphans
```
- 简单验证RESTful API:
- VSCode的REST插件: 见[./dev/manual-test.rest](./dev/manual-test.rest)
- Curl: ```curl -v --request GET --header 'content-type: application/json' --url http://localhost:28080/platform/user/api/v1/rest/user/_/xxx```
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 engineer<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 org.engineer365.platform.user.app.service;
import org.engineer365.platform.user.api.enums.AccountType;
import org.engineer365.platform.user.api.enums.ErrorCode;
import org.engineer365.platform.user.api.req.AccountAuthReq;
import org.engineer365.platform.user.api.req.CreateAccountByEmailReq;
import org.engineer365.platform.user.app.entity.AccountEO;
import org.engineer365.platform.user.app.entity.UserEO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.engineer365.common.error.BadRequestError;
import org.engineer365.common.error.NotFoundError;
import org.engineer365.platform.user.app.dao.AccountDAO;
@Service
@lombok.Setter
@lombok.Getter
public class AccountService {
@Autowired
AccountDAO accountDao;
public AccountEO getAccount(boolean ensureExists, String accountId) {
return getAccountDao().get(ensureExists, accountId);
}
public AccountEO getAccountByEmail(boolean ensureExists, String email) {
var r = getAccountDao().getByCredentialAndType(email, AccountType.EMAIL);
if (r == null && ensureExists) {
throw new NotFoundError(ErrorCode.NO_ACCOUNT_WITH_SPECIFIED_EMAIL);
}
return r;
}
public void checkRequestWithAccount(AccountEO account, AccountAuthReq req) {
if (account == null) {
throw new NotFoundError(ErrorCode.ACCOUNT_NOT_FOUND);
}
if (account.getPassword().equals(req.getPassword()) == false) {
throw new BadRequestError(ErrorCode.WRONG_PASSWORD);
}
}
public String authByAccount(AccountAuthReq req) {
var a = getAccount(false, req.getAccountId());
checkRequestWithAccount(a, req);
return a.getId(); //TODO: replace it with JWT
}
public AccountEO createAccountByEmail(String accountId, CreateAccountByEmailReq req, UserEO user) {
if (getAccountDao().getByCredentialAndType(req.getEmail(), AccountType.EMAIL) != null) {
throw new BadRequestError(ErrorCode.ACCOUNT_EMAIL_DUPLICATES);
}
var r = AccountEO.CREATE_BY_EMAIL_REQ_COPIER.copy(req); {
r.setId(accountId);
r.setUser(user);
}
return getAccountDao().save(r);
}
}
<file_sep>
1. 请Fork这个项目,把你的GITHUB账号名加到[./members.md](./members.md)那个文件,然后提交PR,等待合并。
2. Watch这个项目,任何项目变动都能得到邮件通知。
3. PR合并成功后,加入QQ群1033056382(目前不打算用微信)。加群时需要回答你提交PR时用的GITHUB账号。
4. 入群后,请把你的群内昵称改为GITHUB账号名,否则会被踢出。
5. 可选:Star一下,有助于我们找到更多参与者
QQ群:1033056382(目前不打算用微信)
对这个过程如果有什么问题,可以提交Issue [https://github.com/engineer-365/cloud-native-micro-service-engineering/issues]
| # | GITHUB账号(必填) | 备注(可选) |
| :---: | :----------------------------------- | :---------------------------: |
| 1 | qiangyt | 发起人 |
| 2 | WeiLoongMao | |
| 3 | CNYuYang | |
| 4 | Jason_liu | |
| 5 | zlmkenan001 | |
| 6 | knoxnoe | |
| 7 | wqjzzgci | |
| 8 | greedynamic | |
<file_sep>/*
* MIT License
*
* Copyright (c) 2020 <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 org.engineer365.platform.user.app.service;
import org.engineer365.platform.user.api.enums.AccountType;
import org.engineer365.platform.user.api.enums.ErrorCode;
import org.engineer365.platform.user.api.req.AccountAuthReq;
import org.engineer365.platform.user.api.req.CreateAccountByEmailReq;
import org.engineer365.platform.user.app.dao.AccountDAO;
import org.engineer365.platform.user.app.entity.AccountEO;
import org.engineer365.platform.user.app.entity.UserEO;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.engineer365.common.error.BadRequestError;
import org.engineer365.common.error.NotFoundError;
import org.engineer365.common.service.ServiceTestBase;
public class AccountServiceTest extends ServiceTestBase {
@Mock
AccountDAO accountDao;
@InjectMocks
AccountService target;
@Test
void test_checkRequestWithAccount_ACCOUNT_NOT_FOUND() {
assertThrows (NotFoundError.class, ErrorCode.ACCOUNT_NOT_FOUND,
() -> this.target.checkRequestWithAccount(null, new AccountAuthReq()));
assertThrows (NotFoundError.class, ErrorCode.ACCOUNT_NOT_FOUND,
() -> this.target.checkRequestWithAccount(null, null));
}
@Test
void test_checkRequestWithAccount_PASSWORD_NOT_MATCHES() {
var a = new AccountEO();
a.setPassword("abc");
var req = new AccountAuthReq();
req.setPassword("def");
assertThrows(BadRequestError.class, ErrorCode.WRONG_PASSWORD,
() -> this.target.checkRequestWithAccount(a, req));
}
@Test
void test_checkRequestWithAccount_OK() {
var a = new AccountEO();
a.setPassword("abc");
var req = new AccountAuthReq();
req.setPassword("abc");
this.target.checkRequestWithAccount(a, req);
}
@Test
void test_auth_accountNotFound() {
var req = new AccountAuthReq();
req.setAccountId("a-1");
req.setPassword("p");
when(this.accountDao.get(false, "a-1")).thenReturn(null);
assertThrows(NotFoundError.class, ErrorCode.ACCOUNT_NOT_FOUND,
() -> this.target.authByAccount(req));
}
@Test
void test_auth_ok() {
var req = new AccountAuthReq();
req.setAccountId("a-1");
req.setPassword("p");
var a = new AccountEO();
a.setId("a-1");
a.setPassword("p");
a.setCredential("<EMAIL>");
a.setType(AccountType.EMAIL);
when(this.accountDao.get(false, "a-1")).thenReturn(a);
var r = this.target.authByAccount(req);
Assertions.assertEquals(a.getId(), r);
}
@Test
void test_createAccountByEmail_happy() {
var accountId = "a-1";
var user = new UserEO();
user.setId("u-1");
var req = new CreateAccountByEmailReq();
req.setPassword("p");
req.setUserId(user.getId());
req.setEmail("<EMAIL>");
when(this.accountDao.save(ArgumentMatchers.any())).thenReturn(new AccountEO());
//when(this.emailSender.send(ArgumentMatchers.any())).thenReturn(null);
this.target.createAccountByEmail(accountId, req, user);
verify(this.accountDao).save(argThat((AccountEO entity) -> {
Assertions.assertNotNull(entity.getId());
Assertions.assertEquals(req.getPassword(), entity.getPassword());
Assertions.assertSame(user, entity.getUser());
return true;
}));
}
}
| 939eae6be335a70fddb1e10071169b63667829f4 | [
"Markdown",
"Java",
"Shell",
"SQL"
] | 16 | Java | cyylog/cloud-native-micro-service-engineering | 7d468b5ca8b001309e6d8ae112b4cf1aaea57639 | 45398abd29787b62d5e77c3f86fa36e6bbdb04f5 | |
refs/heads/master | <repo_name>Misowii/CIS423<file_sep>/WebServer/python/engine.py
#!/usr/bin/python
from numpy import loadtxt, append, array;
from Predictors import NaiveBayes;
from pickle import load, dump;
from sys import argv;
import os, urllib, json;
os_bracket = '/';
def loadData(datSRC, delim, typ):
return loadtxt(datSRC, delimiter=delim, dtype = typ);
def googleSearch(search):
'work around for google search api - i think...'
query = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s";#search api? free to use
results = urllib.urlopen( query % (search) );
json_res = json.loads( results.read() );
return int(json_res['responseData']['cursor']['estimatedResultCount']); #returns number of estimated search results
def loadClassifier(objFile, path = 'training-data'):
'loads an already saved classifier, path by default os training data directory'
if os.path.isfile( (path + os_bracket + objFile) ):
return NaiveBayes( load( open(path + os_bracket + objFile) ) );
else:
#print path + os_bracket + objFile;
print '\n[!NO CLASSIFIFER IS SAVED YET!]\n'
return None;
def getClassifier(trainDat = 'train-dat.csv', delim = ',', path = 'training-data'):
'Trains a new classifier, if user does not want ao specific training data, use default'
data = loadData( (path + os_bracket + trainDat) , delim, float); #load training data
nv = NaiveBayes();
nv.summarizeByClass(data); #train classififer
f = open( (path + os_bracket +'classifier.pickle'), 'wb');
dump(nv.summaries, f); #save trained classififer as python pickle
return nv; #return trained classififer
def discretizedFreq(frequency):
if frequency < 1250: return 1;
if frequency < 4500: return 2;
if frequency < 8000: return 3;
if frequency < 16000: return 4;
if frequency < 35000: return 5;
return 6;
def main():
#argv[1] -> name of file that contains user input (should only contain 3 lines)
#srcTxt -> input string user needed to translate - 1st line
#dstTxt -> translated text online app provided - 2nd line
srcTxt = argv[1];
dstTxt = argv[2];
#loadData(argv[1], '\n', str);
classifier = loadClassifier('classifier.pickle');
if classifier is None:
classifier = getClassifier('eng-to-rus.csv');
frequency = discretizedFreq( googleSearch(dstTxt) );
textSize = len(srcTxt);
label, prob = classifier.predict( [textSize, frequency] );
prediction = ''; prob *= 100; #convert prob into a percentage
if label == 1: prediction = 'good';
else: prediction = 'bad';
#print '\n>> source text: %s ' % srcTxt ;
#print '>> translated text: %s' % dstTxt;
print 'Predicted translation type: %s Prediction confidence percentage: %f percent' % prediction, %prob;
#if-condition executes main functions when file used directly
if __name__ == '__main__':
main();
<file_sep>/WebServer/README.md
###Accurp-Engine
About
-----
Collection of machine learning methods to predict a translated text's accuracy.
At the moment the Naive classifier is the onlyone suitable for predicitons. An update to the regression
predictor is pending, (convert it to a beta-regression-model).
How to Use
----------
Please look at engine.py to see how to use the classifier.
Testing the Engine
------------------
Pending
<file_sep>/CIS423ChromeExtension/background.js
chrome.browserAction.onClicked.addListener(function(tab){
var tabURL = "about:black";
chrome.tabs.query({active: true, lastFocusedWindow: true},
(function(arrayOfTabs){
var activeTab = arrayOfTabs[0];
//alert(activeTab.url + " ## ");
tabURL = activeTab.url;
//alert(tabURL);
if (CheckURL(tabURL) == true){
// alert(tabURL); //action when button is pushed and user is on google translate
registerValidityRequest();
}
else{
chrome.tabs.update({url: "https://translate.google.com"});
}
}
)
);
});
function CheckURL(testURL){
var tempURL = "https://translate.google.com/";
for (i = 0; i < tempURL.length; i++){
if (tempURL[i] != testURL[i]){
return false;
}
}
return true;
};
function registerValidityRequest(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
}<file_sep>/CIS423ChromeExtension/todo.txt
todo:
done: get dom
register click event on icon
send http
recive and display<file_sep>/CIS423ChromeExtension/app.js
getSource = function(){return $(document.all[0]).find("#source").val()};
getTranslation = function(){
val = "";
$(document.all[0]).find("#result_box span").each(function(){
val += $(this).html() + " ";
});
return val;
};
checkLanguage = function(){
return false;
}
// utility & testing functions
setSource = function(val){
$(document.all[0]).find("#source").val(val);
}
testFunctions = function(){
console.log("getSource: ", getSource());
console.log("getTranslation: ", getTranslation());
}
// testFunctions();
queryValidator = function(i,o){
var contentType ="application/x-www-form-urlencoded; charset=utf-8";
if(window.XDomainRequest) //for IE8,IE9
contentType = "text/plain";
$.ajax({
url:"https://localhost:3000/results?first=" + getSource() + "&second=" + getTranslation() ,
type:"GET",
contentType:contentType,
success:function(data)
{
alert("Data from Server"+JSON.stringify(data));
},
error:function(jqXHR,textStatus,errorThrown)
{
alert("BAD!! "+errorThrown);
}
});
}
// alert( queryValidator(getSource(), getTranslation()) );
//
// addButton(){
// button = $("body #gt-lang-submit").html();
// ("body #gt-lang-submit").insertAfter(button);
// }
//
//
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
queryValidator(getSource(), getTranslation());
});
| 63d89ed82732732bf45537a37ff3f5642ebffbb4 | [
"Markdown",
"Python",
"JavaScript",
"Text"
] | 5 | Python | Misowii/CIS423 | 20211366c2032f2f19a29802f8f958970a878e82 | 4cb21cf7438339cc7abeee1a9b0960cd0b820251 | |
refs/heads/main | <repo_name>thainvnv/php-mvc-core<file_sep>/README.md
# php-mvc-core | 2cd9d77ec64e8d9525867228692d7e609696ae10 | [
"Markdown"
] | 1 | Markdown | thainvnv/php-mvc-core | 04e2030c8297ba04b460583ddc4ddf6a60b89cc6 | 13d2a40a339cf23eb0f71a6884f22f7d5bff1b3d | |
refs/heads/master | <file_sep>struct node { int key; struct node *next; };
struct node *head, *z, *t;
list_initialize() {
head = (struct node *) malloc(sizeof *head);
z = (struct node *) malloc(sizeof *z);
head->next = z; z->next = z;
}
delete_next(struct node *t) { t->next = t->next->next; }
struct node *insert_after(int v, struct node *t) {
struct node *x;
x = (struct node *) malloc(sizeof *x);
x->key = v; x->next = t->next;
t->next = x;
return x;
}
<file_sep>#define N 1000
main() {
int i, j, a[N + 1];
for (a[1] = 0, i = 2; i <= N; i++) a[i] = 1;
for (i = 2; i <= N/2; i++)
for (j = 2; j <= N/i; j++)
a[i * j] = 0;
for (i = 1; i <= N; i++)
if (a[i]) printf("%4d", i);
printf("\n");
}
| cd865be756b0a2ac867f56954a02b2bb5834c923 | [
"C"
] | 2 | C | jcaudle/sedgewick_algos_c | be4bcc5af5a7da1c94ed95703e35f40ce45d808d | 4725c5c09c0bfe29ed0cc29b34ac2e013e1a2e71 | |
refs/heads/master | <file_sep>// How many paths exist through a given matrix of n*m starting at the top-left when the only possible moves are down and right?
console.log("running");
let N = 3;
let M = 2;
function calculatePaths(n, m) {
console.log("calculatePaths function running");
let rAllowance = n - 1;
let lAllowance = m - 1;
let totalFoundPaths = 0;
let prevPath = [];
let currPath = [];
let currPos = [0, 0];
let currTurn = 0;
let solutionsExhausted = false;
let currPathComplete = false;
while (!solutionsExhausted) {
// run current solution
let rAllowanceCurr = rAllowance;
let lAllowanceCurr = lAllowance;
function isLeftAllowed() {
// console.log(`lAllowanceCurr ${lAllowanceCurr}`);
// console.log(`rAllowanceCurr ${rAllowanceCurr}`);
if (lAllowanceCurr) {
// base case for first run-through
if (!totalFoundPaths) {
return true;
}
return true;
} else {
return false;
}
}
while (!currPathComplete) {
// console.log(`currTurn ${currTurn}`);
console.log(currPath);
if (isLeftAllowed()) {
currPath.push(0);
lAllowanceCurr -= 1;
} else {
currPath.push(1);
rAllowanceCurr -= 1;
}
currTurn += 1;
if (currTurn > rAllowance + lAllowance) {
currPathComplete = true;
prevPath = currPath;
}
}
// check if another solution is to be had
solutionsExhausted = true; // ADD CONDITIONAL FOR MORE THAN ONE RUN-THROUGH OF WHILE LOOP
}
}
calculatePaths(N, M)
<file_sep>function merge(arr1, arr2) {
var result = [];
while (arr1.length && arr2.length) {
result.push(arr1[0] < arr2[0] ? arr1.shift() : arr1.shift());
}
return result.concat(arr1, arr2);
}
<file_sep>inputArr = [1, 2, 3, 4, 5];
answerArr = [1,1,2,6,24];
answer2Arr = [120,60,20,5,1];
ansArr = [];
let runningProduct = 1;
let runningProduct2 = 1;
for (var i = 0; i < inputArr.length; i++) {
if (i > 0) {
runningProduct *= inputArr[i - 1];
}
ansArr[i] = runningProduct;
}
for (var i = inputArr.length - 1; i > -1; i++) {
if (i < inputArr.length - 1) {
runningProduct2 *= inputArr[i + 1];
}
ansArr[i] = runningProduct2;
}
// FORGET
finalArr = [120,60,40,30,24];
// runthrough:
inputArr[2] = 3
runningProduct = 2
| fafdcf77029b0a01024f7e6a586083844af89918 | [
"JavaScript"
] | 3 | JavaScript | nathanalexanderpage/brainteasers | adbd99a19f12921eaa456d41a200b3c13ef16d0a | 066ed1f55f6babeb18a2ec4e5148af79ae8c3d91 | |
refs/heads/master | <file_sep>## Swimmable Rivers data E Coli counts and swimmable categories from the National Rivers Water Quality Network New Zealand Government Clean Water Package 2017
### Description
In March 2017, the National Government announced a consultation over it's proposed [Clean Water package 2017](http://www.mfe.govt.nz/fresh-water/freshwater-management-reforms/clean-water-package-2017).
The package proposed a revised definition of the 'swimmability' of rivers and lakes. The base data were E coli counts from river sampling sites in New Zealand's National Rivers Water Quality Network. The counts were transformed into lengths of river segments (reachs) and the reachs were binned into five categories.
The package included a headline announcement that there would be a 'target', [90% of rivers and lakes would be swimmable by 2040](http://www.mfe.govt.nz/node/22969). The target would be calculated on the basis of lengths of river reachs. The current 'baseline', in lengths of river reachs, was that 72% were 'swimmable'.
On 15 March 2017, I asked the Ministry for the Environment for the underlying sampling data from the water quality monitoring sites ("https://fyi.org.nz/request/5549-clean-water-2017-analysis-of-water-quality-monitoring-sites-making-up-the-water-quality-categories-expressed-in-lengths-of-rivers-swimmable-in-report-me-1293).
On 5 July 2017, after a complaint to the Office of the Ombudsmen, I was emailed the relevant data in .rdata format. I created this repository to provide a permanent and open home for the data.
### Contents
The repository holds the data in .rdata format, the data in .csv format and a very short R script file.
WQdailymeansEcoli.rdata
WQdailymeansEcoli.csv
WQ-daily-means-Ecoli.r<file_sep>load (file="/home/simon/R/bp/WQdailymeansEcoli.rdata", envir=globalenv())
ls()
[1] "WQdailymeansEcoli"
str(WQdailymeansEcoli)
'data.frame': 69819 obs. of 13 variables:
$ sID : Factor w/ 792 levels "ARC-06604","ARC-06804",..: 1 1 1 1 1 1 1 1 1 1 ...
$ rcid : Factor w/ 15 levels "ARC","BOP","ECAN",..: 1 1 1 1 1 1 1 1 1 1 ...
$ srcid : Factor w/ 17 levels "AC","BOP","CCC",..: 1 1 1 1 1 1 1 1 1 1 ...
$ river : Factor w/ 579 levels "Akatarawa River",..: 221 221 221 221 221 221 221 221 221 221 ...
$ location: Factor w/ 741 levels "(Waianiwaniwa R) At Auchenflower Rd",..: 724 724 724 724 724 724 724 724 724 724 ...
$ sitename: Factor w/ 792 levels "Akatarawa River at Hutt Confluence",..: 288 288 288 288 288 288 288 288 288 288 ...
$ nzmge : int 2664055 2664055 2664055 2664055 2664055 2664055 2664055 2664055 2664055 2664055 ...
$ nzmgn : int 6538194 6538194 6538194 6538194 6538194 6538194 6538194 6538194 6538194 6538194 ...
$ nzreach : int 2001381 2001381 2001381 2001381 2001381 2001381 2001381 2001381 2001381 2001381 ...
$ sdate : POSIXct, format: "2006-07-04" "2006-08-01" ...
$ Q : num NA NA NA NA NA NA NA NA NA NA ...
$ npid : chr "ECOLI" "ECOLI" "ECOLI" "ECOLI" ...
$ values : num 204 1200 310 3300 590 127 90 290 690 460 ...
# write as .csv file
write.table(WQdailymeansEcoli, file = "WQdailymeansEcoli.csv", sep = ",", col.names = TRUE, qmethod = "double",row.names = FALSE)
# write as .xls file Excel 2007/10
write.csv(WQdailymeansEcoli, file = "WQdailymeansEcoli.xls", fileEncoding = "UTF-16LE")
head(WQdailymeansEcoli)
sID rcid srcid river location
444 ARC-06604 ARC AC Matakana River Wenzlicks Farm
445 ARC-06604 ARC AC Matakana River Wenzlicks Farm
446 ARC-06604 ARC AC Matakana River Wenzlicks Farm
447 ARC-06604 ARC AC Matakana River Wenzlicks Farm
448 ARC-06604 ARC AC Matakana River Wenzlicks Farm
449 ARC-06604 ARC AC Matakana River Wenzlicks Farm
sitename nzmge nzmgn nzreach sdate Q
444 Matakana River at Wenzlicks Farm 2664055 6538194 2001381 2006-07-04 NA
445 Matakana River at Wenzlicks Farm 2664055 6538194 2001381 2006-08-01 NA
446 Matakana River at Wenzlicks Farm 2664055 6538194 2001381 2006-09-06 NA
447 Matakana River at Wenzlicks Farm 2664055 6538194 2001381 2006-10-03 NA
448 Matakana River at Wenzlicks Farm 2664055 6538194 2001381 2006-11-09 NA
449 Matakana River at Wenzlicks Farm 2664055 6538194 2001381 2006-12-05 NA
npid values
444 ECOLI 204
445 ECOLI 1200
446 ECOLI 310
447 ECOLI 3300
448 ECOLI 590
449 ECOLI 127
getwd()
[1] "/home/simon/R"
setwd("/home/simon/R/bp")
getwd()
[1] "/home/simon/R/bp"
write.csv(WQdailymeansEcoli, file = "WQdailymeansEcoli.csv",row.names=FALSE)
write.csv(WQdailymeansEcoli, file = "WQdailymeansEcoli.csv",row.names=FALSE)
# To upload a file, run the following command in xterminal :
simon@I6:~
$ cd /home/simon/R/bp/
simon@I6:~/R/bp
$ gdrive upload WQdailymeansEcoli.rdata
Uploading WQdailymeansEcoli.rdata
Uploaded 0B8LhMBA3NXL4SUx5OXlLaXJndGs at 123.2 KB/s, total 503.2 KB
simon@I6:~/R/bp
gdrive upload WQdailymeansEcoli.rdata
| 4ea8e328c34b4fbb780363a1470474e03aa7cf0f | [
"R",
"RMarkdown"
] | 2 | RMarkdown | theecanmole/WQ-daily-means-Ecoli-NZ-WQ-daily-means-Ecoli.r | af3fef2211b40dccb217f8c3c404478cda552237 | 9a7a786225aa3f2f750079b5bb815f3d16d77fca | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace MVCBase.Areas.SuperAdmin.Public
{
public class SuperAdminCommon
{
/// <summary>
/// 生成初始化JS,用于初始化左侧栏焦点位置
/// </summary>
/// <param name="LI_ID"></param>
/// <param name="A_ID"></param>
/// <returns></returns>
public static string JSInit(string LI_ID, string A_ID)
{
StringBuilder sbjs = new StringBuilder();
sbjs.Append("$(\"#" + LI_ID + "\").addClass(\"current\");" + System.Environment.NewLine);
sbjs.Append("$(\"#" + A_ID + "\").addClass(\"current\");" + System.Environment.NewLine);
sbjs.Append("$(\"#main-nav li a.current\").parent().find(\"ul\").slideToggle(\"slow\");" + System.Environment.NewLine);
return sbjs.ToString();
}
}
}<file_sep>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace MVCBase.Common
{
public class Encrypt
{
/// <summary>
/// 当前程序加密所使用的密钥
/// </summary>
public static readonly string sKey = "vingi3DESLDHzt/pRr/TOGSJPXANLG51";
#region 加密方法
/// <summary>
/// 加密方法
/// </summary>
/// <param name="pToEncrypt">需要加密字符串</param>
/// <param name="sKey">密钥</param>
/// <returns>加密后的字符串</returns>
public static string DESEncrypt(string pToEncrypt)
{
try
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = Convert.FromBase64String(sKey);
des.Mode = CipherMode.ECB;
byte[] valBytes = Encoding.Unicode.GetBytes(pToEncrypt);
ICryptoTransform transform = des.CreateEncryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
cs.Write(valBytes, 0, valBytes.Length);
cs.FlushFinalBlock();
byte[] returnBytes = ms.ToArray();
cs.Close();
return Convert.ToBase64String(returnBytes);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write("写入配置信息失败,详细信息:" + ex.Message.Replace("\r\n", "").Replace("'", ""));
}
return "";
}
#endregion
#region 解密方法
/// <summary>
/// 解密方法
/// </summary>
/// <param name="pToDecrypt">需要解密的字符串</param>
/// <param name="sKey">密匙</param>
/// <returns>解密后的字符串</returns>
public static string DESDecrypt(string pToDecrypt)
{
try
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = Convert.FromBase64String(sKey);
des.Mode = CipherMode.ECB;
byte[] valBytes = Convert.FromBase64String(pToDecrypt);
ICryptoTransform transform = des.CreateDecryptor();
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write);
cs.Write(valBytes, 0, valBytes.Length);
cs.FlushFinalBlock();
byte[] returnBytes = ms.ToArray();
cs.Close();
return Encoding.Unicode.GetString(returnBytes);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write("读取配置信息失败,详细信息:" + ex.Message.Replace("\r\n", "").Replace("'", ""));
}
return "";
}
#endregion
#region MD5编码方法
/// <summary>
/// MD5编码方法
/// </summary>
/// <param name="pToDecrypt">需要编码的字符串</param>
/// <returns>编码后的字符串</returns>
public static string MD5Encrypt(string pToEncrypt)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(pToEncrypt, "MD5");
}
#endregion
#region SHA1编码方法
/// <summary>
/// MD5编码方法
/// </summary>
/// <param name="pToDecrypt">需要编码的字符串</param>
/// <returns>编码后的字符串</returns>
public static string SHA1Encrypt(string pToEncrypt)
{
return FormsAuthentication.HashPasswordForStoringInConfigFile(pToEncrypt, "SHA1");
}
#endregion
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace MVCBase.Common
{
public class HtmlPagerControl
{
private string _clickevent;
private int _current_page = 1;
private int _display_count = 5;
private int _display_page_count;
private string _href_page = string.Empty;
private List<HtmlPageInfo> _items = new List<HtmlPageInfo>();
private int _left_display_number;
private string _middle_seperator = "...";
private int _page_count;
private int _right_display_number;
private int _step;
private int _totalcount;
private string _totalpageid = string.Empty;
public HtmlPagerControl(int pageCount, int display_page_count, int totalcount)
{
this._page_count = pageCount;
this._display_page_count = display_page_count;
this._totalcount = totalcount;
this._step = display_page_count / 2;
}
public void Add(HtmlPageInfo info)
{
try
{
info.CurrentPage = this._current_page;
this._items.Add(info);
}
catch
{
throw new Exception("类型不匹配");
}
}
private void Init()
{
HtmlPageInfo info;
HtmlPageInfo info2;
HtmlPageInfo info3;
HtmlPageInfo info4;
if ((this._current_page - this._step) < 1)
{
this._left_display_number = 1;
this._right_display_number = (this._left_display_number + this._display_page_count) - 1;
}
else
{
this._left_display_number = this._current_page - this._step;
this._right_display_number = this._current_page + this._step;
}
if (this._right_display_number >= this._page_count)
{
this._right_display_number = this._page_count;
this._left_display_number = ((this._right_display_number - this._display_page_count) <= 0) ? 1 : (this._right_display_number - (this._display_page_count - 1));
}
if ((this._right_display_number - this._left_display_number) == this._display_page_count)
{
this._right_display_number--;
}
if (this._current_page > 1)
{
info = new HtmlPageInfo();
info.CurrentPage = this._current_page;
info.HrefPage = this._href_page;
info.ClickEvent = this._clickevent;
info.IndexPage = 1;
info.Text = "首頁";
info.Width = 50;
info2 = new HtmlPageInfo();
info2.CurrentPage = this._current_page;
info2.IndexPage = this._current_page - 1;
info2.HrefPage = this._href_page;
info2.ClickEvent = this._clickevent;
info2.Text = "上一頁";
info2.Width = 50;
}
else
{
info = null;
info2 = null;
}
if (this._current_page < this._page_count)
{
info3 = new HtmlPageInfo();
info3.CurrentPage = this._current_page;
info3.HrefPage = this._href_page;
info3.ClickEvent = this._clickevent;
info3.IndexPage = this._current_page + 1;
info3.Text = "下一頁";
info3.Width = 50;
info4 = new HtmlPageInfo();
info4.CurrentPage = this._current_page;
info4.HrefPage = this._href_page;
info4.ClickEvent = this._clickevent;
info4.IndexPage = this._page_count;
info4.Text = "末頁";
info4.Width = 50;
}
else
{
info4 = null;
info3 = null;
}
if (info != null)
{
this._items.Add(info);
}
if (info2 != null)
{
this._items.Add(info2);
}
for (int i = this._left_display_number; i <= this._right_display_number; i++)
{
HtmlPageInfo item = new HtmlPageInfo();
item.IndexPage = i;
if (this._href_page.EndsWith("/"))
{
this._href_page.Remove(this._href_page.Length - 1, 1);
}
item.HrefPage = this._href_page;
item.ClickEvent = this._clickevent;
item.CurrentPage = this._current_page;
item.IndexPage = i;
this._items.Add(item);
}
if (info3 != null)
{
this._items.Add(info3);
}
if (info4 != null)
{
this._items.Add(info4);
}
}
private List<int> ListPage(int current, int place, bool reverse)
{
List<int> list = new List<int>();
while (current != place)
{
list.Add(current);
if (reverse)
{
current++;
}
else
{
current--;
}
}
return list;
}
public void RemoveAll()
{
this._items.Clear();
}
public string Render()
{
this.Init();
StringBuilder builder = new StringBuilder();
builder.Append("<div style=\"text-align: center;margin: 10px;\">");
if (this._page_count > 1)
{
//builder.Append("<div style=\"text-align: center;margin: 10px;font-family: 黑体;\"><div style=\"float: left;\">總 <span style=\"color: red;\">" + this._totalcount.ToString() + "</span> 筆</div><div style=\"float: right;\">共 <span id=\"" + this._totalpageid + "\" style=\"color: red;\">" + this._page_count.ToString() + "</span> 頁</div>");
foreach (HtmlPageInfo info in this._items)
{
builder.Append(info.Render());
}
}
//else
//{
// builder.Append("<div style=\"text-align: center;margin: 10px;font-family: 黑体;\"><div style=\"float: left;\">總 <span style=\"color: red;\">" + this._totalcount.ToString() + "</span> 筆</div><div style=\"float: right;\">共 <span id=\"" + this._totalpageid + "\" style=\"color: red;\">" + this._page_count.ToString() + "</span> 頁</div>");
//}
builder.Append("<div style=\"clear: both;\"></div></div>");
return builder.ToString();
}
public string ClickEvent
{
get
{
return this._clickevent;
}
set
{
this._clickevent = value;
}
}
public int CurrentPage
{
get
{
return this._current_page;
}
set
{
if (value > this._page_count)
{
this._current_page = this._page_count;
}
else if (value < 1)
{
this._current_page = 1;
}
else
{
this._current_page = value;
}
}
}
public int Displaycount
{
get
{
return this._display_count;
}
set
{
this._display_count = value;
}
}
public string HrefPage
{
get
{
return this._href_page;
}
set
{
this._href_page = value;
}
}
public HtmlPageInfo this[int index]
{
get
{
if ((index >= this._page_count) || (index < 0))
{
throw new Exception("索引超出大小");
}
return this._items[index];
}
}
public List<HtmlPageInfo> Items
{
get
{
return this._items;
}
set
{
this._items = value;
}
}
public int left_display_number
{
get
{
return this._left_display_number;
}
}
public string MiddleSeperator
{
get
{
return this._middle_seperator;
}
set
{
this._middle_seperator = value;
}
}
public int PageCount
{
get
{
return this._page_count;
}
}
public int right_display_number
{
get
{
return this._right_display_number;
}
}
public int step
{
get
{
return this._step;
}
}
public string TotalPageId
{
get
{
return this._totalpageid;
}
set
{
this._totalpageid = value;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Areas.SuperAdmin.Controllers
{
public class MediumListController : Controller
{
//
// GET: /SuperAdmin/MediumList/
public ActionResult Index()
{
ViewBag.jsInit = Public.SuperAdminCommon.JSInit("MediumManage", "MediumList");
Medium dal = new Medium();
IList<Ba_Medium> medium = dal.Getmedium();
return View(medium);
}
}
}
<file_sep>using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVCBase.DAL
{
public class News
{
ISession session;
public News()
{
session = (new NHibernateHelper()).GetSession();
}
public void Add(Ba_News news)
{
session.Save(news);
session.Flush();
}
public void Update(Ba_News news)
{
session.Update(news);
session.Flush();
}
public void SaveOrUpdate(Ba_News news)
{
session.SaveOrUpdate(news);
session.Flush();
}
public Ba_News GetSingleNewsById(int Ns_ID)
{
return session.Get<Ba_News>(Ns_ID);
}
public IList<Ba_News> GetNews()
{
return session.CreateQuery("from Ba_News as ns where ns.Ns_State=:st")
.SetBoolean("st", true).List<Ba_News>();
}
public IList<Ba_News> GetNews(int pagenum)
{
int pagestep = 3;
return session.CreateQuery("from Ba_News as ns where ns.Ns_State=:st order by ns.Ns_BuildTime desc")
.SetBoolean("st", true)
.SetFirstResult((pagenum - 1) * pagestep)
.SetMaxResults(pagenum * pagestep)
.List<Ba_News>();
}
}
}
<file_sep>HAICHI
======
海基<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
namespace MVCBase.DAL
{
class NHibernateHelper
{
private ISessionFactory _sessionFactory;
private string path = System.Web.HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml");
public NHibernateHelper()
{
_sessionFactory = GetSessionFactory();
}
private ISessionFactory GetSessionFactory()
{
return (new Configuration()).Configure(path).BuildSessionFactory();
}
public ISession GetSession()
{
Configuration cfg = new Configuration().Configure(path);
ISession session = cfg.BuildSessionFactory().OpenSession();
return session;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace MVCBase.Common
{
public class TRIP3DES
{
//密钥
private string sKey = "<KEY>";
//矢量,矢量可以为空
private string sIV = "vingiDES";
//构造一个对称算法
private SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
public TRIP3DES(string _sKey, string _sIV)
{
sKey = _sKey;
sIV = _sIV;
}
#region public string EncryptString(string Value)
///
/// 加密字符串
///
/// 输入的字符串
/// 加密后的字符串
public string EncryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
mCSP.Key = Convert.FromBase64String(sKey);
mCSP.IV = Convert.FromBase64String(sIV);
//指定加密的运算模式
mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
//获取或设置加密算法的填充模式
mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
byt = Encoding.UTF8.GetBytes(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
//return Convert.ToBase64String(ms.ToArray());
//return Convert.ToChar(ms.ToArray()).ToString();
string strResult = "";
byte[] b = ms.ToArray();
for (int i = 0; i < b.Length; i++)
{
strResult += b[i].ToString("x").PadLeft(2, '0');
}
return strResult;
}
#endregion
#region public string DecryptString(string Value)
///
/// 解密字符串
///
/// 加过密的字符串
/// 解密后的字符串
public string DecryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
mCSP.Key = Convert.FromBase64String(sKey);
mCSP.IV = Convert.FromBase64String(sIV);
mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
//byt = Convert.FromBase64String(Value);
byt = new byte[Value.Length / 2];
int bi = 0;
for (int i = 0; i < Value.Length; i += 2)
{
byt[bi] = (byte)Int32.Parse(Value.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
bi++;
}
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
#endregion
}
}<file_sep>using System;
namespace MVCBase.Domain.Entity
{
public class Ba_Medium
{
/// <summary>
/// Ns_ID
/// </summary>
public virtual int Ns_ID { get; set; }
/// <summary>
/// Ns_Title
/// </summary>
public virtual string Ns_Title { get; set; }
/// <summary>
/// Ns_SubTitle
/// </summary>
public virtual string Ns_SubTitle { get; set; }
/// <summary>
/// Ns_Content
/// </summary>
public virtual string Ns_Content { get; set; }
/// <summary>
/// Ns_BuildTime
/// </summary>
public virtual DateTime? Ns_BuildTime { get; set; }
/// <summary>
/// Ns_State
/// </summary>
public virtual bool Ns_State { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Controllers
{
public class HomeController : Controller
{
private static log4net.ILog log = log4net.LogManager.GetLogger("Quote");
public ActionResult Index()
{
//ViewBag.Message = "欢迎使用 ASP.NET MVC!";
////Sample dal = new Sample();
////var customer = dal.GetCustomerById(3);
////customer.FirstName = "Vingi";
////customer.LastName = "Chen";
////dal.UpdateCustomer(customer);
//Admin dal = new Admin();
//var model = dal.GetAdminById(1);
//ViewBag.Message = model.Ad_AdminPwd;
//ViewBag.Model = model;
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult Product()
{
return View();
}
public ActionResult Key()
{
return View();
}
public ActionResult People()
{
return View();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Controllers
{
public class ListController : Controller
{
//
// GET: /List/
public ActionResult News(int? id)
{
News dal = new News();
IList<Ba_News> model = dal.GetNews(id.HasValue ? (int)id : 1);
IList<Ba_News> allmodel = dal.GetNews();
int pagenum = 1;
if (allmodel.Count % 3 == 0)
pagenum = allmodel.Count / 3;
else
pagenum = allmodel.Count / 3 + 1;
int currentpage = id.HasValue ? (int)id : 1;
Common.HtmlPagerControl page = new Common.HtmlPagerControl(pagenum, 3, 7);
page.CurrentPage = currentpage;
ViewBag.currentpage = currentpage;
page.ClickEvent = "onclick=\"topage(this);\"";
ViewBag.pageinfo = page.Render();
return View(model);
}
public ActionResult Medium(int? id)
{
Medium dal = new Medium();
IList<Ba_Medium> model = dal.Getmedium(id.HasValue ? (int)id : 1);
IList<Ba_Medium> allmodel = dal.Getmedium();
int pagenum = 1;
if (allmodel.Count % 3 == 0)
pagenum = allmodel.Count / 3;
else
pagenum = allmodel.Count / 3 + 1;
int currentpage = id.HasValue ? (int)id : 1;
Common.HtmlPagerControl page = new Common.HtmlPagerControl(pagenum, 3, 7);
page.CurrentPage = currentpage;
ViewBag.currentpage = currentpage;
page.ClickEvent = "onclick=\"topage(this);\"";
ViewBag.pageinfo = page.Render();
return View(model);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
namespace MVCBase.API
{
/// <summary>
/// StaticRequestHandler 的摘要说明
/// </summary>
public class StaticRequestHandler : IHttpHandler
{
/// <summary>
/// 静态文件合并处理程式
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
//该处理程式因含有敏感字符,故不经过XSS过滤
string type = !string.IsNullOrWhiteSpace(context.Request.QueryString["type"]) ? context.Request.QueryString["type"] : string.Empty;
switch (type)
{
case "css":
context.Response.ContentType = "text/css";
break;
case "js":
context.Response.ContentType = "text/javascript";
break;
case "javascript":
context.Response.ContentType = "text/javascript";
break;
default:
context.Response.ContentType = "text/css";
break;
}
//该处理程式因含有敏感字符,故不经过XSS过滤
string files_str = !string.IsNullOrWhiteSpace(context.Request.QueryString["f"]) ? context.Request.QueryString["f"] : string.Empty;
string[] files = files_str.Split(',');
for (int i = 0; i < files.Length; ++i)
{
if (!string.IsNullOrWhiteSpace(files[i]) && (files[i].EndsWith(".css") || files[i].EndsWith(".js")))
{
try
{
string path = System.Web.HttpContext.Current.Server.MapPath(files[i].StartsWith("~/") ? files[i] : context.Request.ApplicationPath + "/" + files[i]);
StreamReader sr = new StreamReader(path, Encoding.GetEncoding("UTF-8"), false);
context.Response.Write(sr.ReadToEnd() + Environment.NewLine);
context.Response.Expires = 60 * 24 * 30; //30天过期
sr.Close();
sr.Dispose();
}
catch (Exception) { }
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}<file_sep>using System;
using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MVCBase.DAL
{
public class Medium
{
ISession session;
public Medium()
{
session = (new NHibernateHelper()).GetSession();
}
public void Add(Ba_Medium medium)
{
session.Save(medium);
session.Flush();
}
public void Update(Ba_Medium medium)
{
session.Update(medium);
session.Flush();
}
public void SaveOrUpdate(Ba_Medium medium)
{
session.SaveOrUpdate(medium);
session.Flush();
}
public Ba_Medium GetSinglemediumById(int Ns_ID)
{
return session.Get<Ba_Medium>(Ns_ID);
}
public IList<Ba_Medium> Getmedium()
{
return session.CreateQuery("from Ba_Medium as ns where ns.Ns_State=:st")
.SetBoolean("st", true).List<Ba_Medium>();
}
public IList<Ba_Medium> Getmedium(int pagenum)
{
int pagestep = 3;
return session.CreateQuery("from Ba_Medium as ns where ns.Ns_State=:st order by ns.Ns_BuildTime desc")
.SetBoolean("st", true)
.SetFirstResult((pagenum - 1) * pagestep)
.SetMaxResults(pagenum * pagestep)
.List<Ba_Medium>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Areas.SuperAdmin.Controllers
{
public class NewsOperateController : Controller
{
//
// GET: /SuperAdmin/NewsOperate/
public ActionResult Index(int? id)
{
ViewBag.jsInit = Public.SuperAdminCommon.JSInit("NewsManage", "NewsOperate");
var model = new Ba_News();
if (id != null)
{
News dal = new News();
model = dal.GetSingleNewsById((int)id);
}
if (model == null)
model = new Ba_News();
ViewBag.model = model;
if (model.Ns_ID.Equals(0))
ViewBag.Title = "新增最新消息";
else
ViewBag.Title = "更新最新消息";
return View();
}
[HttpPost,ValidateInput(false)]
public string Submit(NewsOperate_Form form)
{
string result = string.Empty;
News dal = new News();
var model = dal.GetSingleNewsById(form.news_id);
if (model == null)
model = new Ba_News();
model.Ns_Title = form.news_title;
model.Ns_SubTitle = form.news_subtitle;
model.Ns_Content = form.news_description;
model.Ns_BuildTime = DateTime.Now;
model.Ns_State = true;
try
{
dal.SaveOrUpdate(model);
result = "1";
}
catch (System.Exception ex)
{
result = ex.ToString();
}
return result;
}
public string Delete(int id)
{
string result = "0";
News dal = new News();
var model = dal.GetSingleNewsById(id);
if (model != null)
{
model.Ns_State = false;
dal.Update(model);
result = "1";
}
return result;
}
}
public class NewsOperate_Form
{
public int news_id { get; set; }
public string news_title { get; set; }
public string news_subtitle { get; set; }
public string news_description { get; set; }
}
}
<file_sep>using MVCBase.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using System.Configuration;
namespace MVCBase.Areas.SuperAdmin.Controllers
{
public class LoginController : Controller
{
//
// GET: /SuperAdmin/Login/
public ActionResult Index()
{
return View();
}
[HttpPost]
public string Login(SuperAdmin superadmin)
{
string str = string.Empty;
if (superadmin.Verify())
{
str = Login(superadmin.LoginName, superadmin.Password) ? "1" : "2";
}
return str;
}
[NonAction]
public bool Login(string LoginName, string Password)
{
bool istrue = false;
Admin dal = new Admin();
IList<Ba_Admin> admins = dal.GetModel(LoginName, Common.Encrypt.MD5Encrypt(Password));
istrue = admins.Count > 0 ? true : false;
if (istrue)
{
//更新最后login时间
admins[0].Ad_LastLoginTime = DateTime.Now;
dal.Update(admins[0]);
//写入cookies
setcookie(admins[0]);
}
return istrue;
}
//设置cookies
public void setcookie(Ba_Admin entity)
{
string _domain = ConfigurationManager.AppSettings["WebDomain"];
HttpCookieCollection cookiecollect = new HttpCookieCollection();
HttpCookie Account = null;
HttpCookie Username = null;
if (!string.IsNullOrEmpty(entity.Ad_AdminName))
{
Account = new HttpCookie("SuperAccount", Encrypt.DESEncrypt(entity.Ad_AdminName + System.Configuration.ConfigurationManager.AppSettings["AccountKey"]));
Username = new HttpCookie("Superusername", entity.Ad_AdminName);
}
cookiecollect.Add(Account);
cookiecollect.Add(Username);
for (int i = 0; i < cookiecollect.Count; i++)
{
if (!_domain.Equals("localhost"))
cookiecollect[i].Domain = _domain;
System.Web.HttpContext.Current.Response.Cookies.Add(cookiecollect[i]);
}
}
}
public class SuperAdmin
{
public string LoginName { get; set; }
public string Password { get; set; }
//验证返回数据的正确性
public bool Verify()
{
bool istrue = true;
//验证数据是否异常
if (string.IsNullOrEmpty(this.LoginName) ||
string.IsNullOrEmpty(this.Password))
{
istrue = false;
}
return istrue;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;
namespace MVCBase.DAL
{
public class Admin
{
ISession session;
public Admin()
{
session = (new NHibernateHelper()).GetSession();
}
public void CreateAdmin(Ba_Admin admin)
{
session.Save(admin);
session.Flush();
}
public Ba_Admin GetAdminById(int Ad_ID)
{
//Configuration cfg = new Configuration().Configure(path);
//ISession session = cfg.BuildSessionFactory().OpenSession();
return session.Get<Ba_Admin>(Ad_ID);
}
public void Update(Ba_Admin admin)
{
session.Update(admin);
session.Flush();
}
public IList<Ba_Admin> GetModel(string adminname, string adminpwd)
{
//session.Get<Ba_Admin>()
return session.CreateQuery("from Ba_Admin as ad where ad.Ad_AdminName=:an and ad.Ad_AdminPwd=:ap")
.SetString("an", adminname).SetString("ap", adminpwd).List<Ba_Admin>();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using MVCBase.Domain.Entity;
namespace MVCBase.DAL
{
public class Sample
{
ISession session;
public Sample()
{
session = (new NHibernateHelper()).GetSession();
}
public void CreateCustomer(Customer customer)
{
//Configuration cfg = new Configuration().Configure(path);
//ISession session = (new NHibernateHelper()).GetSession();
session.Save(customer);
session.Flush();
}
public void UpdateCustomer(Customer customer)
{
//ISession session = (new NHibernateHelper()).GetSession();
session.SaveOrUpdate(customer);
session.Flush();
}
public Customer GetCustomerById(int customerId)
{
//Configuration cfg = new Configuration().Configure(path);
//ISession session = cfg.BuildSessionFactory().OpenSession();
return session.Get<Customer>(customerId);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Areas.SuperAdmin.Controllers
{
public class NewsListController : Controller
{
//
// GET: /SuperAdmin/NewsList/
public ActionResult Index()
{
ViewBag.jsInit = Public.SuperAdminCommon.JSInit("NewsManage", "NewsList");
News dal = new News();
IList<Ba_News> news = dal.GetNews();
ViewBag.news = news;
return View(news);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Areas.SuperAdmin.Controllers
{
public class MediumOperateController : Controller
{
//
// GET: /SuperAdmin/MediumOperate/
public ActionResult Index(int? id)
{
ViewBag.jsInit = Public.SuperAdminCommon.JSInit("MediumManage", "MediumOperate");
var model = new Ba_Medium();
if (id != null)
{
Medium dal = new Medium();
model = dal.GetSinglemediumById((int)id);
}
if (model == null)
model = new Ba_Medium();
ViewBag.model = model;
if (model.Ns_ID.Equals(0))
ViewBag.Title = "新增媒體報道";
else
ViewBag.Title = "更新媒體報道";
return View();
}
[HttpPost,ValidateInput(false)]
public string Submit(MediumOperate_Form form)
{
string result = string.Empty;
Medium dal = new Medium();
var model = dal.GetSinglemediumById(form.medium_id);
if (model == null)
model = new Ba_Medium();
model.Ns_Title = form.medium_title;
model.Ns_SubTitle = form.medium_subtitle;
model.Ns_Content = form.medium_description;
model.Ns_BuildTime = DateTime.Now;
model.Ns_State = true;
try
{
dal.SaveOrUpdate(model);
result = "1";
}
catch (System.Exception ex)
{
result = ex.ToString();
}
return result;
}
public string Delete(int id)
{
string result = "0";
Medium dal = new Medium();
var model = dal.GetSinglemediumById(id);
if (model != null)
{
model.Ns_State = false;
dal.Update(model);
result = "1";
}
return result;
}
}
public class MediumOperate_Form
{
public int medium_id { get; set; }
public string medium_title { get; set; }
public string medium_subtitle { get; set; }
public string medium_description { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCBase.Domain.Entity;
using MVCBase.DAL;
using NHibernate;
namespace MVCBase.Controllers
{
public class DetailController : Controller
{
//
// GET: /Detail/
public ActionResult News(int? id)
{
News dal = new News();
Ba_News model = dal.GetSingleNewsById(id.HasValue ? (int)id : 1);
return View(model);
}
public ActionResult Medium(int? id)
{
Medium dal = new Medium();
Ba_Medium model = dal.GetSinglemediumById(id.HasValue ? (int)id : 1);
return View(model);
}
}
}
<file_sep>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
namespace MVCBase.Common
{
public class Database
{
private string sConnectionString = "";
private SqlConnection Conn;
public Database() { }
public Database(string strcon)
{
sConnectionString = strcon;
}
public string StrCon
{
get
{
return sConnectionString;
}
set
{
sConnectionString = value;
}
}
public void Conncetion()
{
if (sConnectionString == "" || sConnectionString == null)
{
sConnectionString = "";
}
}
private void Open()
{
Conncetion();
Conn = new SqlConnection(sConnectionString);
if (Conn.State == ConnectionState.Closed)
Conn.Open();
}
public void Close()
{
if (Conn != null)
{
if (Conn.State == ConnectionState.Open)
Conn.Close();
Conn.Dispose();
Conn = null;
}
}
private void Dispose()
{
if (Conn != null)
Conn.Dispose();
Conn = null;
}
public SqlDataReader ExecuteReader(string cmdText, CommandType cmdType)
{
this.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
try
{
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
this.Close();
return null;
}
}
public SqlDataReader ExecuteReader(string cmdText, CommandType cmdType, params SqlParameter[] CmdParams)
{
this.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
if (CmdParams != null)
{
foreach (SqlParameter Param in CmdParams)
{
cmd.Parameters.Add(Param);
}
}
try
{
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return reader;
}
catch
{
this.Close();
return null;
}
}
public DataSet GetDataSet(string cmdText, CommandType cmdType)
{
Conncetion();
SqlCommand cmd = new SqlCommand();
using (SqlConnection Conn = new SqlConnection(sConnectionString))//调用完直接释放资源 适用与非连接环境
{
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
DataSet ds = new DataSet();
try
{
ada.Fill(ds);
}
catch (SqlException)
{
}
return ds;
}
}
public DataSet GetDataSet(string cmdText, CommandType cmdType, SqlParameter[] adaParams)
{
Conncetion();
SqlCommand cmd = new SqlCommand();
using (SqlConnection Conn = new SqlConnection(sConnectionString))
{
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
SqlDataAdapter ada = new SqlDataAdapter();
if (adaParams != null)
{
foreach (SqlParameter Param in adaParams)
{
cmd.Parameters.Add(Param);
}
}
ada.SelectCommand = cmd;
DataSet ds = new DataSet();
try
{
ada.Fill(ds);
}
catch (SqlException)
{
}
cmd.Parameters.Clear();
return ds;
}
}
public DataTable GetDataTable(string cmdText)
{
DataTable tempdt = new DataTable();
try
{
tempdt = GetDataSet(cmdText, CommandType.Text).Tables[0];
}
catch (Exception)
{
}
return tempdt;
}
public DataTable GetDataTable(string cmdText, CommandType cmdType)
{
DataTable tempdt = new DataTable();
try
{
tempdt = GetDataSet(cmdText, cmdType).Tables[0];
}
catch (Exception)
{
}
return tempdt;
}
public DataTable GetDataTable(string cmdText, CommandType cmdType, SqlParameter[] adaParams)
{
return GetDataSet(cmdText, cmdType, adaParams).Tables[0];
}
public int ExecuteNonQuery(string cmdText, CommandType cmdType)
{
int i;
try
{
this.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
i = cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
throw e;
}
finally
{
this.Close();
}
return i;
}
public int ExecuteNonQuery(string cmdText, CommandType cmdType, SqlParameter[] cmdParams)
{
int i;
try
{
this.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
foreach (SqlParameter Param in cmdParams)
{
cmd.Parameters.Add(Param);
}
i = cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
throw e;
}
finally
{
this.Close();
}
return i;
}
public int ExecuteReturnValue(string cmdText, CommandType cmdType)
{
SqlCommand cmd;
try
{
this.Open();
cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
cmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
throw e;
}
finally
{
this.Close();
}
return (int)cmd.Parameters["ReturnValue"].Value;
}
public int ExecuteReturnValue(string cmdText, CommandType cmdType, SqlParameter[] cmdParams)
{
SqlCommand cmd;
try
{
this.Open();
cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
foreach (SqlParameter Param in cmdParams)
{
cmd.Parameters.Add(Param);
}
cmd.Parameters.Add(new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
throw e;
}
finally
{
this.Close();
}
return (int)cmd.Parameters["ReturnValue"].Value;
}
public object ExecuteScalar(string cmdText)
{
object o;
try
{
this.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = cmdText;
o = cmd.ExecuteScalar();
}
catch (SqlException e)
{
throw e;
}
finally
{
this.Close();
}
return o;
}
public object ExecuteScalar(string cmdText, CommandType cmdType)
{
object o;
try
{
this.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
o = cmd.ExecuteScalar();
}
catch (SqlException e)
{
throw e;
}
finally
{
this.Close();
}
return o;
}
public object ExecuteScalar(string cmdText, CommandType cmdType, SqlParameter[] cmdParams)
{
object o;
SqlCommand cmd = new SqlCommand();
try
{
this.Open();
cmd.Connection = Conn;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
foreach (SqlParameter Param in cmdParams)
{
cmd.Parameters.Add(Param);
}
o = cmd.ExecuteScalar();
}
catch (SqlException e)
{
throw e;
}
finally
{
cmd.Parameters.Clear();
this.Close();
}
return o;
}
//------------------------------------------------------------------------------------
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <returns>是否执行成功</returns>
public bool RunProc(string procName)
{
try
{
SqlCommand cmd = CreateCommand(procName, null, CommandType.StoredProcedure);
cmd.ExecuteNonQuery();
return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value) == 0 ? true : false;
}
catch { return false; }
finally
{
Close();
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
/// <returns>是否执行成功</returns>
public int RunProc(string procName, SqlParameter[] prams)
{
try
{
SqlCommand cmd = CreateCommand(procName, prams, CommandType.StoredProcedure);
cmd.ExecuteNonQuery();
return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value);
}
catch (Exception ex)
{
string s = ex.Message;
return 0;
}
finally
{
Close();
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <param name="dataReader">SqlDataReader 用来接受存储过程索取的数据集</param>
/// <returns>是否执行成功</returns>
public bool RunProc(string procName, out SqlDataReader dataReader)
{
try
{
SqlCommand cmd = CreateCommand(procName, null, CommandType.StoredProcedure);
dataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return true;
}
catch
{
dataReader = null;
return false;
}
finally
{
Close();
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
/// <param name="dataReader">SqlDataReader 用来接受存储过程索取的数据集</param>
/// <returns>是否执行成功</returns>
public bool RunProc(string procName, SqlParameter[] prams, out SqlDataReader dataReader)
{
try
{
SqlCommand cmd = CreateCommand(procName, prams, CommandType.StoredProcedure);
dataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
return true;
}
catch { dataReader = null; return false; }
finally
{
Close();
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <param name="dataset">DataSet 用来接受存储过程索取的数据集</param>
/// <returns>是否执行成功</returns>
public bool RunProc(string procName, out DataSet dataset)
{
try
{
SqlCommand cmd = CreateCommand(procName, null, CommandType.StoredProcedure);
SqlDataAdapter da = new SqlDataAdapter(cmd);
dataset = new DataSet();
da.Fill(dataset);
return true;
}
catch { dataset = null; return false; }
finally
{
Close();
}
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="procName">存储过程名</param>
/// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
/// <param name="dataset">DataSet 用来接受存储过程索取的数据集</param>
/// <returns>是否执行成功</returns>
public bool RunProc(string procName, SqlParameter[] prams, out DataSet dataset)
{
try
{
SqlCommand cmd = CreateCommand(procName, prams, CommandType.StoredProcedure);
SqlDataAdapter da = new SqlDataAdapter(cmd);
dataset = new DataSet();
da.Fill(dataset);
return true;
}
catch { dataset = null; return false; }
finally
{
Close();
}
}
/// <summary>
/// 为存储过程创建 SqlCommand 对象
/// </summary>
/// <param name="procName_sSQL">要创建 SqlCommand 对象的存储过程名---///---或者是 普通的SQL 语句(含sql参数)</param>
/// <param name="prams">存储过程所需的 sql 参数数组 SqlParameter[]</param>
/// <returns>创建 SqlCommand 对象</returns>
private SqlCommand CreateCommand(string procName_sSQL, SqlParameter[] prams, CommandType cmdType)
{
// 确认已经打开 数据连接对象 SqlConnection
Open();
SqlCommand cmd = new SqlCommand(procName_sSQL, Conn);
cmd.CommandType = cmdType;
// 向SqlCommand 对象 添加sql 参数
if (prams != null)
{
foreach (SqlParameter parameter in prams)
cmd.Parameters.Add(parameter);
}
if (cmdType == CommandType.StoredProcedure)
{
// 向SqlCommand 对象 添加返回值 sql 参数 ---- ReturnValue
cmd.Parameters.Add(
new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0,
string.Empty, DataRowVersion.Default, null));
}
return cmd;
}
/// <summary>
/// 执行存储过程(支持 事务 SqlTransaction)
/// </summary>
/// <param name="transaction">SqlTransaction 事务对象</param>
/// <param name="procName">存储过程名</param>
/// <param name="prams">执行该存储过程所需要的 sql 参数数组 SqlParameter[]</param>
/// <returns></returns>
public bool RunProc(SqlTransaction transaction, string procName, SqlParameter[] prams)
{
try
{
SqlCommand cmd = CreateCommand(transaction, procName, prams, CommandType.StoredProcedure);
cmd.ExecuteNonQuery();
return Convert.ToInt32(cmd.Parameters["ReturnValue"].Value) == 0 ? true : false;
}
catch { return false; }
finally
{
Close();
}
}
/// <summary>
/// 为存储过程创建 SqlCommand 对象 (支持 事务 SqlTransaction)
/// </summary>
/// <param name="transaction">SqlTransaction 事务对象</param>
/// <param name="procName_sSQL">存储过程名---///---或者是 普通的SQL 语句(含sql参数)</param>
/// <param name="prams">存储过程所需要的 sql 参数数组 SqlParameter[]</param>
/// <returns></returns>
private SqlCommand CreateCommand(SqlTransaction transaction, string procName_sSQL, SqlParameter[] prams, CommandType cmdType)
{
// 确认已经打开 数据连接对象 SqlConnection
if (transaction.Connection.State != ConnectionState.Open)
{
transaction.Connection.ConnectionString = StrCon.ToString();
transaction.Connection.Open();
}
SqlCommand cmd = new SqlCommand(procName_sSQL, transaction.Connection, transaction);
cmd.CommandType = cmdType;
//-- 向SqlCommand 对象 添加sql 参数
if (prams != null)
{
foreach (SqlParameter parameter in prams)
cmd.Parameters.Add(parameter);
}
if (cmdType == CommandType.StoredProcedure)
{
// 向SqlCommand 对象 添加返回值 sql 参数 ---- ReturnValue
cmd.Parameters.Add(
new SqlParameter("ReturnValue", SqlDbType.Int, 4,
ParameterDirection.ReturnValue, false, 0, 0,
string.Empty, DataRowVersion.Default, null));
}
return cmd;
}
/// <summary>
/// 创建存储过程/命令文本的 sql 输入参数(SqlParameter)
/// </summary>
/// <param name="ParamName">参数名</param>
/// <param name="DbType">参数类型</param>
/// <param name="Size">参数数值范围</param>
/// <param name="Value">参数值</param>
/// <returns>构造出输入参数</returns>
public SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
{
return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
}
/// <summary>
/// 创建存储过程/命令文本的 sql 输出参数(SqlParameter)
/// </summary>
/// <param name="ParamName">参数名</param>
/// <param name="DbType">参数类型</param>
/// <param name="Size">参数数值范围</param>
/// <returns>构造出输出参数</returns>
public SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
{
return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
}
/// <summary>
/// 创建存储过程/命令文本的 sql 参数(SqlParameter)
/// </summary>
/// <param name="ParamName">参数名</param>
/// <param name="DbType">参数类型</param>
/// <param name="Size">参数数值范围</param>
/// <param name="Direction">参数操作形式</param>
/// <param name="Value">参数值</param>
/// <returns>构造出 SqlParameter</returns>
public SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
{
SqlParameter param;
if (Size > 0)
param = new SqlParameter(ParamName, DbType, Size);
else
param = new SqlParameter(ParamName, DbType);
param.Direction = Direction;
if (!(Direction == ParameterDirection.Output && Value == null))
param.Value = Value;
return param;
}
public DataSet ExecuteNonQuery(string SqlStr)
{
//sConncetion();
SqlConnection SqlCon = new SqlConnection(sConnectionString);
SqlCon.Open();
SqlCommand SqlCom = new SqlCommand(SqlStr.ToString(), SqlCon);
SqlCom.CommandType = CommandType.Text;
//SqlCom.ExecuteNonQuery();
DataSet ObjDs = new DataSet();
SqlDataAdapter SqlDa = new SqlDataAdapter(SqlCom);
SqlDa.Fill(ObjDs);
SqlCon.Close();
return ObjDs;
}
}
}<file_sep>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Text;
using System.Drawing;
using System.Xml;
using System.Collections;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace MVCBase.Common
{
public class common
{
private static log4net.ILog log = log4net.LogManager.GetLogger("common");
#region 防止XSS注入 获取request
/// <summary>
/// 防止XSS注入 获取request
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string request(string str)
{
string returnstr = string.Empty;
if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request[str]))
returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request[str].Trim());
return returnstr;
}
public static string requestForm(string str)
{
string returnstr = string.Empty;
if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.Form[str]))
returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request.Form[str].Trim());
return returnstr;
}
public static string requestQueryString(string str)
{
string returnstr = string.Empty;
if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.QueryString[str]))
returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request.QueryString[str].Trim());
return returnstr;
}
public static string requestCookies(string str)
{
string returnstr = string.Empty;
if (System.Web.HttpContext.Current.Request.Cookies[str] != null)
returnstr = XSSInject.XSSInject.FilterXSS(System.Web.HttpContext.Current.Request.Cookies[str].Value.Trim());
return returnstr;
}
#endregion
#region 过滤SQL注入;
/// <summary>
/// 过滤SQL注入;
/// </summary>
/// <param name="str">传入string进行SQL过滤</param>
public static string Sqlstr(string str)
{
str = str.Trim();
if (str == "" || str == string.Empty || str == null)
return "";
str = str.Replace(';', ';');
str = str.Replace('(', '(');
str = str.Replace(')', ')');
return str;
}
#endregion
#region 执行正则提取出值
//执行正则提取出值#region 执行正则提取出值
/**/
/**********************************
* 函数名称:GetRegValue
* 功能说明:执行正则提取出值
* 参 数:HtmlCode:html源代码
* 调用示例:
* string GetValue=GetRegValue(Reg,HtmlCode)
* Response.Write(GetValue);
* ********************************/
/**/
/// <summary>
/// 执行正则提取出值
/// </summary>
/// <param name="Reg">正则表达式</param>
/// <param name="HtmlCode">HtmlCode源代码</param>
/// <returns></returns>
public static string GetRegValue(string RegexString, string RemoteStr)
{
string MatchVale = "";
//string MatchVale = "0"; //为预防正则匹配为空值,导致insert into失败而修改
Regex r = new Regex(RegexString);
Match m = r.Match(RemoteStr);
if (m.Success)
{
MatchVale = m.Value;
}
return MatchVale.Replace("\r", "").Replace("\n", "");
}
#endregion
}
}<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace MVCBase.Areas.SuperAdmin.Public
{
/// <summary>
/// UploadHandler 的摘要说明
/// </summary>
public class UploadHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
HttpPostedFile oFile = context.Request.Files["Filedata"];
string strUploadPath = HttpContext.Current.Server.MapPath("/ImageUpload") + "\\";
if (oFile != null)
{
if (!Directory.Exists(strUploadPath))
{
Directory.CreateDirectory(strUploadPath);
}
Random ro = new Random();
string stro = ro.Next(100, 100000000).ToString();//产生一个随机数用于新命名的图片
string NewName = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;
if (oFile.FileName.Length > 0)
{
string FileExtention = Path.GetExtension(oFile.FileName);
string fileallname = strUploadPath + NewName + FileExtention;
oFile.SaveAs(fileallname);
//异步到image server
try
{
//string re = Upload_Request("http://vingi.soufun.tw/ReceiveImage.ashx?filename=" + NewName + "_1" + FileExtention, fileallname, NewName + FileExtention, context);
//string re = uploadtt(fileallname);
string re = "/ImageUpload/" + NewName + FileExtention;
if (string.IsNullOrEmpty(Common.common.requestQueryString("immediate")))
{
context.Response.Write(re);
}
else
{
context.Response.Write("{\"err\":\"\",\"msg\":\"" + re + "\"}");
}
//FileInfo file = new FileInfo(fileallname);
//file.Delete();
context.Response.End();
}
catch (Exception ex) { }
}
}
else
{
context.Response.Write("0");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace MVCBase.Common
{
public class HtmlPageInfo : ICloneable
{
private Dictionary<string, string> _attributes = new Dictionary<string, string>();
private string _clickevent = string.Empty;
private int _current_page = 1;
private string _href_page = string.Empty;
private int _index_page = 1;
private string _mouseout = "this.style.backgroundColor='#ffffff';this.style.color='#000000';this.style.border='1px solid #cccccc';";
private string _mouseover = "this.style.backgroundColor='#cccccc';this.style.color='#FF7F00';this.style.border='1px solid #999999';";
private string _text = string.Empty;
private int _width = 0x19;
public void AddAttribute(object dictionary)
{
Type type = dictionary.GetType();
if (type != null)
{
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo info in properties)
{
string str = "";
str = info.GetValue(dictionary, null).ToString();
try
{
this._attributes.Remove(info.Name.Replace("_", "-"));
}
catch
{
}
this._attributes.Add(info.Name.Replace("_", "-"), str);
}
}
}
public object Clone()
{
return base.MemberwiseClone();
}
private string CreateStyle()
{
StringBuilder builder = new StringBuilder();
builder.Append("");
if (this._attributes.Count > 0)
{
foreach (KeyValuePair<string, string> pair in this._attributes)
{
builder.Append(pair.Key + ":" + pair.Value);
builder.Append(";");
}
}
return builder.ToString();
}
public string Render()
{
if (this._index_page <= 0)
{
this._index_page = 1;
}
StringBuilder builder = new StringBuilder();
if (!this._text.Equals("首頁") && !this._text.Equals("末頁"))
{
builder.Append("<span " + this._clickevent + " ");
if (this._text.Equals("下一頁"))
builder.Append(" class=\"page_r\" ");
else if (this._text.Equals("上一頁"))
builder.Append(" class=\"page_l\" ");
else
builder.Append(" class=\"page_p\" id=\"page" + this._index_page.ToString() + "\" ");
builder.Append(this.CreateStyle());
builder.Append(">");
//builder.Append(string.IsNullOrEmpty(this._text) ? this._index_page.ToString() : this._text);
builder.Append("</span>");
}
return builder.ToString();
}
public string ClickEvent
{
get
{
return this._clickevent;
}
set
{
this._clickevent = value;
}
}
public int CurrentPage
{
get
{
return this._current_page;
}
set
{
this._current_page = value;
}
}
public string HrefPage
{
get
{
return this._href_page;
}
set
{
this._href_page = value;
}
}
public int IndexPage
{
get
{
return this._index_page;
}
set
{
this._index_page = value;
}
}
public string MouseOut
{
get
{
return this._mouseout;
}
set
{
this._mouseout = value;
}
}
public string MouseOver
{
get
{
return this._mouseover;
}
set
{
this._mouseover = value;
}
}
public string Text
{
get
{
return this._text;
}
set
{
this._text = value;
}
}
public int Width
{
get
{
return this._width;
}
set
{
if (value <= 10)
{
this._width = value;
}
else
{
this._width = value;
}
}
}
}
}<file_sep>using System;
namespace MVCBase.Domain.Entity
{
public class Ba_Admin
{
/// <summary>
/// Ad_ID
/// </summary>
public virtual int Ad_ID { get; set; }
/// <summary>
/// Ad_AdminName
/// </summary>
public virtual string Ad_AdminName { get; set; }
/// <summary>
/// Ad_AdminPwd
/// </summary>
public virtual string Ad_AdminPwd { get; set; }
/// <summary>
/// Ad_LastLoginTime
/// </summary>
public virtual DateTime? Ad_LastLoginTime { get; set; }
/// <summary>
/// Ad_BuildTime
/// </summary>
public virtual DateTime? Ad_BuildTime { get; set; }
/// <summary>
/// Ad_State
/// </summary>
public virtual int? Ad_State { get; set; }
}
}<file_sep>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace MVCBase.Common.SqlInject
{
public class SqlstrAny : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += (new
EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source, EventArgs e)
{
ProcessRequest pr = new ProcessRequest();
pr.StartProcessRequest();
}
public void Dispose()
{
}
}
public class ProcessRequest
{
private static string SqlStr = System.Configuration.ConfigurationManager.AppSettings["SqlInject"].ToString();
private static string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["SQLInjectErrPage"].ToString();
///
/// 用来识别是否是流的方式传输
///
///
///
bool IsUploadRequest(HttpRequest request)
{
return StringStartsWithAnotherIgnoreCase(request.ContentType, "multipart/form-data");
}
///
/// 比较内容类型
///
///
///
///
private static bool StringStartsWithAnotherIgnoreCase(string s1, string s2)
{
return (string.Compare(s1, 0, s2, 0, s2.Length, true, System.Globalization.CultureInfo.InvariantCulture) == 0);
}
//SQL注入式攻击代码分析
#region SQL注入式攻击代码分析
///
/// 处理用户提交的请求
///
public void StartProcessRequest()
{
HttpRequest Request = System.Web.HttpContext.Current.Request;
HttpResponse Response = System.Web.HttpContext.Current.Response;
try
{
string getkeys = "";
if (IsUploadRequest(Request)) return; //如果是流传递就退出
//字符串参数
if (Request.QueryString != null)
{
for (int i = 0; i < Request.QueryString.Count; i++)
{
getkeys = Request.QueryString.Keys[i];
if (!ProcessSqlStr(Request.QueryString[getkeys]))
{
Response.Redirect(sqlErrorPage + "?errmsg=QueryString中含有非法字符串&sqlprocess=true");
Response.End();
}
}
}
//form参数
if (Request.Form != null)
{
for (int i = 0; i < Request.Form.Count; i++)
{
getkeys = Request.Form.Keys[i];
if (!ProcessSqlStr(Request.Form[getkeys]))
{
Response.Redirect(sqlErrorPage + "?errmsg=Form中含有非法字符串&sqlprocess=true");
Response.End();
}
}
}
//cookie参数
if (Request.Cookies != null)
{
for (int i = 0; i < Request.Cookies.Count; i++)
{
getkeys = Request.Cookies.Keys[i];
if (!ProcessSqlStr(Request.Cookies[getkeys].Value))
{
Response.Redirect(sqlErrorPage + "?errmsg=Cookie中含有非法字符串&sqlprocess=true");
Response.End();
}
}
}
}
catch(Exception ex)
{
// 错误处理: 处理用户提交信息!
if (!(ex is HttpRequestValidationException))
{
Response.Clear();
Response.Write("CustomErrorPage配置错误");
Response.End();
}
}
}
///
/// 分析用户请求是否正常
///
/// 传入用户提交数据
/// 返回是否含有SQL注入式攻击代码
private bool ProcessSqlStr(string Str)
{
bool ReturnValue = true;
try
{
if (Str != "")
{
string[] anySqlStr = SqlStr.Split('|');
foreach (string ss in anySqlStr)
{
if (Str.IndexOf(ss) >= 0)
{
ReturnValue = false;
break;
}
}
}
}
catch
{
ReturnValue = false;
}
return ReturnValue;
}
#endregion
}
}
| 05672d18129fdc77b656e05cc6f0c42d579517ec | [
"Markdown",
"C#"
] | 26 | C# | vingi/HAICHI | 6ed5d73da7abe6320511ce327d2ee936847d4a90 | 3588bb4c799fd229ad216987dc8d62b653d9ca3d | |
refs/heads/master | <repo_name>abindef/AbpCoreDemo<file_sep>/src/Alilimi.BookStore.Web/Properties/AssemblyInfo.cs
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleToAttribute("Alilimi.BookStore.Web.Tests")]
<file_sep>/src/Alilimi.BookStore.Application/Properties/AssemblyInfo.cs
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleToAttribute("Alilimi.BookStore.Application.Tests")]
<file_sep>/src/Alilimi.BookStore.EntityFrameworkCore/Properties/AssemblyInfo.cs
using System.Runtime.CompilerServices;
[assembly:InternalsVisibleToAttribute("Alilimi.BookStore.EntityFrameworkCore.Tests")]
<file_sep>/src/Alilimi.BookStore.Web/Controllers/AccountController.cs
using Volo.Abp.AspNetCore.Mvc.Authentication;
namespace Alilimi.BookStore.Web.Controllers
{
public class AccountController : ChallengeAccountController
{
}
} | 5468c3e880a9b8a0215d2ef9360aebb45937d97b | [
"C#"
] | 4 | C# | abindef/AbpCoreDemo | 2e5f127af92c176e45dd6cfd517237f41fb8d5fe | b652b0f9b4093365166d2229cd8977adc4e4a32d | |
refs/heads/master | <repo_name>LavanyaSrini/Machine_learning<file_sep>/Eigen_KNN.py
#run Eigen_KNN.py
#from sklearn.metrics import accuracy_score
#accuracy_score(label_p, predictions)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from PIL import Image
from imutils import paths
import numpy as np
import argparse
import os
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
import scipy.linalg as la
import cv2
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, default="Gallery_GENI",
help="path to directory containing the 'Gallery' dataset")
ap.add_argument("-d1", "--dataset1", type=str, default="Probe_GENI",
help="path to directory containing the 'Probe' dataset1")
ap.add_argument("-m", "--model", type=str, default="knn",
help="type of python machine learning model to use")
args = vars(ap.parse_args())
models = {
"knn": KNeighborsClassifier(n_neighbors=1),
}
imagePaths = paths.list_images(args["dataset"])
X_data = []
labels = []
for imagePath in imagePaths:
image = Image.open(imagePath)
image=np.array(image)
X_data.append(image)
label = imagePath.split(os.path.sep)[-2]
labels.append(label)
X_data=np.array(X_data)
n_samples = X_data.shape[0]
pca = PCA()
X_data=X_data.reshape(X_data.shape[0],X_data.shape[1]*X_data.shape[2])
X_centered = X_data - np.mean(X_data, axis=0)
cov_matrix = np.dot(X_centered.T, X_centered) / n_samples
evals, evecs = np.linalg.eig(cov_matrix)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]
variance_retained=np.cumsum(evals)/np.sum(evals)
var_per=.98
index=np.argmax(variance_retained>=var_per)
evecs = evecs[:,:index+1]
reduced_data=np.dot(evecs.T, X_data.T).T
clf=PCA(var_per)
X_train=X_data
X_train=clf.fit_transform(X_train)
le = LabelEncoder()
labels = le.fit_transform(labels)
model = models[args["model"]]
model.fit(X_train,labels)
#-------------------------
imagePaths1 = paths.list_images(args["dataset1"])
X_data1 = []
label_p = []
for imagePath1 in imagePaths1:
image1 = Image.open(imagePath1)
image1 = np.array(image1)
X_data1.append(image1)
label1 = imagePath1.split(os.path.sep)[-2]
label_p.append(label1)
X_data1=np.array(X_data1)
n_samples1 = X_data1.shape[0]
pca1 = PCA()
X_data1 = X_data1.reshape(X_data1.shape[0],X_data1.shape[1]*X_data1.shape[2])
X_test1=clf.transform(X_data1)
le = LabelEncoder()
label_p = le.fit_transform(label_p)
predictions = model.predict(X_test1)
print(predictions)
<file_sep>/README.md
# Machine_learning
Simple_classifier.py
Extract mean and standard deviation as features and classify using knn, lda, svm...
PCA_KNN.py
Extract features using standard pca and classify using knn.
Eigen_PCA.py
Extract features by calculating covmatrix,eigen values and eigen vectors calculate pca and classify using knn.
Try with data provided in Zip files.
<file_sep>/PCA_KNN.py
# large dataset is vertorized and detect using knn
#run PCA_KNN.py
#from sklearn.metrics import accuracy_score
#accuracy_score(label_p, predictions)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from PIL import Image
from imutils import paths
import numpy as np
import argparse
import os
from sklearn.metrics import accuracy_score
from sklearn.decomposition import PCA
import scipy.linalg as la
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, default="Gallery",
help="path to directory containing the 'Gallery' dataset")
ap.add_argument("-d1", "--dataset1", type=str, default="Probe",
help="path to directory containing the 'Probe' dataset1")
ap.add_argument("-m", "--model", type=str, default="knn",
help="type of python machine learning model to use")
args = vars(ap.parse_args())
models = {
"knn": KNeighborsClassifier(n_neighbors=1),
}
imagePaths = paths.list_images(args["dataset"])
X_data = []
labels = []
for imagePath in imagePaths:
image = Image.open(imagePath)
image=np.array(image)
X_data.append(image)
label = imagePath.split(os.path.sep)[-2]
labels.append(label)
X_data=np.array(X_data)
X_data=X_data.reshape(X_data.shape[0],X_data.shape[1]*X_data.shape[2])
X_mean=np.mean(X_data)
X_data=X_data-X_mean
X_data= np.array(X_data)
pca = PCA(.80)
principalComponents1 = pca.fit_transform(X_data)
le = LabelEncoder()
labels = le.fit_transform(labels)
print(labels)
print("[INFO] using '{}' model".format(args["model"]))
model = models[args["model"]]
model.fit(X_data,labels)
imagePaths1 = paths.list_images(args["dataset1"])
X_data1 = []
label_p = []
for imagePath1 in imagePaths1:
image1 = Image.open(imagePath1)
image1 = np.array(image1)
X_data1.append(image1)
label1 = imagePath1.split(os.path.sep)[-2]
label_p.append(label1)
X_data1=np.array(X_data1)
X_data1=X_data1.reshape(X_data1.shape[0],X_data1.shape[1]*X_data1.shape[2])
X_mean1=np.mean(X_data1)
X_data1=X_data1-X_mean1
X_data1= np.array(X_data1)
pca = PCA(.80)
principalComponents2 = pca.fit_transform(X_data1)
print(principalComponents2.shape)
le = LabelEncoder()
label_p = le.fit_transform(label_p)
predictions = model.predict(X_data1)
print(predictions)
<file_sep>/Simple_classifier.py
# Split train and test dataset and run all classifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from PIL import Image
from imutils import paths
import numpy as np
import argparse
import os
def extract_color_stats(image):
features = [np.mean(image), np.std(image),
]
return features
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", type=str, default="3scenes",
help="path to directory containing the '3scenes' dataset")
ap.add_argument("-m", "--model", type=str, default="knn",
help="type of python machine learning model to use")
args = vars(ap.parse_args())
models = {
"knn": KNeighborsClassifier(n_neighbors=1),
"naive_bayes": GaussianNB(),
"logit": LogisticRegression(solver="lbfgs", multi_class="auto"),
"svm": SVC(kernel="linear"),
"decision_tree": DecisionTreeClassifier(),
"random_forest": RandomForestClassifier(n_estimators=100),
"mlp": MLPClassifier(),
"lda": LinearDiscriminantAnalysis()
}
#print("[INFO] extracting image features...")
imagePaths = paths.list_images(args["dataset"])
data = []
labels = []
for imagePath in imagePaths:
image = Image.open(imagePath)
features = extract_color_stats(image)
data.append(features)
label = imagePath.split(os.path.sep)[-2]
labels.append(label)
le = LabelEncoder()
labels = le.fit_transform(labels)
(trainX, testX, trainY, testY) = train_test_split(data, labels,
test_size=0.50)
print("[INFO] using '{}' model".format(args["model"]))
model = models[args["model"]]
model.fit(trainX, trainY)
print("[INFO] evaluating...")
predictions = model.predict(testX)
print(classification_report(testY, predictions,
target_names=le.classes_))
results = confusion_matrix(testY, predictions)
print('confusion_matrix',results)
| 0b7dc4fa254b8216a808988494a94cd78efbaefe | [
"Markdown",
"Python"
] | 4 | Python | LavanyaSrini/Machine_learning | 656dda4c93527b4a9cbd330aaab9679c09c9d9f0 | 6707bdb8eab7684cdd76b86580fe2e29688c75a0 | |
refs/heads/master | <file_sep>"""A flexible and expressive pandas validation library."""
from . import errors, constants
from .checks import Check
from .hypotheses import Hypothesis
from .decorators import check_input, check_output
from .dtypes import (
PandasDtype,
Bool,
DateTime,
Category,
Float,
Int,
Object,
String,
Timedelta,
)
from .schemas import DataFrameSchema, SeriesSchema
from .schema_components import Column, Index, MultiIndex
__version__ = "0.3.0"
<file_sep>.. pandera documentation for seriesschemas
.. _SeriesSchemas:
Series Schemas
==============
``SeriesSchema``\s allow for the validation of ``pd.Series`` objects, and
are very similar to :ref:`columns<column>` and :ref:`indexes<index>` described
in :ref:`DataFrameSchemas<DataFrameSchemas>`.
.. testcode:: series_validation
import pandas as pd
import pandera as pa
from pandera import Check, SeriesSchema
# specify multiple validators
schema = SeriesSchema(
pa.String,
checks=[
Check(lambda s: s.str.startswith("foo")),
Check(lambda s: s.str.endswith("bar")),
Check(lambda x: len(x) > 3, element_wise=True)
],
nullable=False,
allow_duplicates=True,
name="my_series")
validated_series = schema.validate(
pd.Series(["foobar", "foobar", "foobar"], name="my_series"))
print(validated_series)
.. testoutput:: series_validation
0 foobar
1 foobar
2 foobar
Name: my_series, dtype: object
<file_sep>"""Tests a variety of python and pandas dtypes, and tests some specific
coercion examples."""
import pandas as pd
import pytest
from pandera import (
Column, DataFrameSchema, Check, DateTime, Float, Int,
String, Bool, Category, Object, Timedelta)
from pandera import dtypes
from pandera.errors import SchemaError
TESTABLE_DTYPES = [
(Bool, "bool"),
(DateTime, "datetime64[ns]"),
(Category, "category"),
(Float, "float64"),
(Int, "int64"),
(Object, "object"),
(String, "object"),
(Timedelta, "timedelta64[ns]"),
("bool", "bool"),
("datetime64[ns]", "datetime64[ns]"),
("category", "category"),
("float64", "float64"),
]
def test_numeric_dtypes():
"""Test every numeric type can be validated properly by schema.validate"""
for dtype in [
dtypes.Float,
dtypes.Float16,
dtypes.Float32,
dtypes.Float64]:
assert all(
isinstance(
schema.validate(
pd.DataFrame(
{"col": [-123.1, -7654.321, 1.0, 1.1, 1199.51, 5.1]},
dtype=dtype.value)),
pd.DataFrame
)
for schema in [
DataFrameSchema({"col": Column(dtype, nullable=False)}),
DataFrameSchema({"col": Column(dtype.value, nullable=False)})
]
)
for dtype in [
dtypes.Int,
dtypes.Int8,
dtypes.Int16,
dtypes.Int32,
dtypes.Int64]:
assert all(
isinstance(
schema.validate(
pd.DataFrame(
{"col": [-712, -4, -321, 0, 1, 777, 5, 123, 9000]},
dtype=dtype.value)),
pd.DataFrame
)
for schema in [
DataFrameSchema({"col": Column(dtype, nullable=False)}),
DataFrameSchema({"col": Column(dtype.value, nullable=False)})
]
)
for dtype in [
dtypes.UInt8,
dtypes.UInt16,
dtypes.UInt32,
dtypes.UInt64]:
assert all(
isinstance(
schema.validate(
pd.DataFrame(
{"col": [1, 777, 5, 123, 9000]},
dtype=dtype.value)),
pd.DataFrame
)
for schema in [
DataFrameSchema({"col": Column(dtype, nullable=False)}),
DataFrameSchema({"col": Column(dtype.value, nullable=False)})
]
)
def test_category_dtype():
"""Test the category type can be validated properly by schema.validate"""
schema = DataFrameSchema(
columns={
"col": Column(
dtypes.Category,
checks=[
Check(lambda s: set(s) == {"A", "B", "C"}),
Check(lambda s:
s.cat.categories.tolist() == ["A", "B", "C"]),
Check(lambda s: s.isin(["A", "B", "C"]))
],
nullable=False
),
},
coerce=False
)
validated_df = schema.validate(
pd.DataFrame(
{"col": pd.Series(["A", "B", "A", "B", "C"], dtype="category")}
)
)
assert isinstance(validated_df, pd.DataFrame)
def test_category_dtype_coerce():
"""Test coercion of the category type is validated properly by
schema.validate and fails safely."""
columns = {
"col": Column(
dtypes.Category,
checks=Check(lambda s: set(s) == {"A", "B", "C"}),
nullable=False
),
}
with pytest.raises(SchemaError):
DataFrameSchema(columns=columns, coerce=False).validate(
pd.DataFrame(
{"col": pd.Series(["A", "B", "A", "B", "C"], dtype="object")}
)
)
validated_df = DataFrameSchema(columns=columns, coerce=True).validate(
pd.DataFrame(
{"col": pd.Series(["A", "B", "A", "B", "C"], dtype="object")}
)
)
assert isinstance(validated_df, pd.DataFrame)
def test_datetime():
"""Test datetime types can be validated properly by schema.validate"""
schema = DataFrameSchema(
columns={
"col": Column(
dtypes.DateTime,
checks=Check(lambda s: s.min() > pd.Timestamp("2015")),
)
}
)
validated_df = schema.validate(
pd.DataFrame(
{"col": pd.to_datetime(["2019/01/01", "2018/05/21", "2016/03/10"])}
)
)
assert isinstance(validated_df, pd.DataFrame)
with pytest.raises(SchemaError):
schema.validate(
pd.DataFrame(
{"col": pd.to_datetime(["2010/01/01"])}
)
)
<file_sep>.PHONY: docs tests upload-pypi conda-build-35 conda-build-36 conda-build-37
tests:
pytest
clean:
python setup.py clean
clean-pyc:
find . -name '*.pyc' -exec rm {} \;
upload-pypi-test:
python setup.py sdist bdist_wheel && \
twine upload --repository-url https://test.pypi.org/legacy/ dist/* && \
rm -rf dist
upload-pypi:
python setup.py sdist bdist_wheel && \
twine upload dist/* && \
rm -rf dist
requirements:
pip install -r requirements-dev.txt
docs:
make -C docs doctest && python -m sphinx -E -W "docs/source" "docs/_build"
mock-ci-tests:
. ./ci_tests.sh
conda-build: conda-build-35 conda-build-36 conda-build-37
conda-build-35:
conda-build --python=3.5 conda.recipe
conda-build-36:
conda-build --python=3.6 conda.recipe
conda-build-37:
conda-build --python=3.7 conda.recipe
<file_sep>"""pandera-specific errors."""
class SchemaInitError(Exception):
"""Raised when schema initialization fails."""
class SchemaDefinitionError(Exception):
"""Raised when schema definition is invalid on object validation."""
class SchemaError(Exception):
"""Raised when object does not pass schema validation constraints."""
<file_sep>"""Schema datatypes."""
# pylint: disable=C0103
from enum import Enum
class PandasDtype(Enum):
"""Enumerate all valid pandas data types."""
Bool = "bool"
DateTime = "datetime64[ns]"
Category = "category"
Float = "float64"
Float16 = "float16"
Float32 = "float32"
Float64 = "float64"
Int = "int64"
Int8 = "int8"
Int16 = "int16"
Int32 = "int32"
Int64 = "int64"
UInt8 = "uint8"
UInt16 = "uint16"
UInt32 = "uint32"
UInt64 = "uint64"
Object = "object"
# the string datatype doesn't map to a unique string representation and is
# representated as a numpy object array. This will change after pandas 1.0,
# but for now will need to handle this as a special case.
String = "string"
Timedelta = "timedelta64[ns]"
Bool = PandasDtype.Bool
DateTime = PandasDtype.DateTime
Category = PandasDtype.Category
Float = PandasDtype.Float
Float16 = PandasDtype.Float16
Float32 = PandasDtype.Float32
Float64 = PandasDtype.Float64
Int = PandasDtype.Int
Int8 = PandasDtype.Int8
Int16 = PandasDtype.Int16
Int32 = PandasDtype.Int32
Int64 = PandasDtype.Int64
UInt8 = PandasDtype.UInt8
UInt16 = PandasDtype.UInt16
UInt32 = PandasDtype.UInt32
UInt64 = PandasDtype.UInt64
Object = PandasDtype.Object
String = PandasDtype.String
Timedelta = PandasDtype.Timedelta
<file_sep>.. pandera documentation for Checks
.. _checks:
Checks
======
Checking column properties
--------------------------
:class:`~pandera.checks.Check` objects accept a function as a required argument, which
is expected to have the following signature:
``pd.Series -> bool|pd.Series[bool]``.
For the :class:`~pandera.checks.Check` to pass, all of the elements in the boolean
series must evaluate to ``True``.
.. testcode:: checks
import pandera as pa
from pandera import Column, Check, DataFrameSchema
schema = DataFrameSchema({"column1": Column(pa.Int, Check(lambda s: s <= 10))})
Multiple checks can be applied to a column:
.. testcode:: checks
schema = DataFrameSchema({
"column2": Column(pa.String, [
Check(lambda s: s.str.startswith("value")),
Check(lambda s: s.str.split("_", expand=True).shape[1] == 2)
]),
})
Built-in Checks
---------------
For common validation tasks built-in checks are available in ``pandera``.
They are provided as factory methods in the :class:`~pandera.checks.Check` class.
This way comparison operations, string validations and whitelisting or blacklisting
of allowed values can be done more easily:
.. testcode:: builtin_checks
import pandera as pa
from pandera import Column, Check, DataFrameSchema
schema = DataFrameSchema({
"small_values": Column(pa.Float, [Check.less_than(100)]),
"one_to_three": Column(pa.Int, [Check.isin([1, 2, 3])]),
"phone_number": Column(pa.String, [Check.str_matches(r'^[a-z0-9-]+$')]),
})
Vectorized vs. Element-wise Checks
----------------------------------
By default, :class:`~pandera.checks.Check` objects operate on ``pd.Series`` objects.
If you want to make atomic checks for each element in the Column, then you can provide
the ``element_wise=True`` keyword argument:
.. testcode:: vectorized_element_wise_checks
import pandas as pd
import pandera as pa
from pandera import Column, Check, DataFrameSchema
schema = DataFrameSchema({
"a": Column(
pa.Int,
[
# a vectorized check that returns a bool
Check(lambda s: s.mean() > 5, element_wise=False),
# a vectorized check that returns a boolean series
Check(lambda s: s > 0, element_wise=False),
# an element-wise check that returns a bool
Check(lambda x: x > 0, element_wise=True),
]
),
})
df = pd.DataFrame({"a": [4, 4, 5, 6, 6, 7, 8, 9]})
schema.validate(df)
``element_wise == False`` by default so that you can take advantage of the
speed gains provided by the ``pd.Series`` API by writing vectorized
checks.
.. _grouping:
Column Check Groups
-------------------
:class:`~pandera.schema_components.Column` checks support grouping by a different column so that
you can make assertions about subsets of the :class:`~pandera.schema_components.Column` of interest.
This changes the function signature of the :class:`~pandera.checks.Check` function so that
its input is a dict where keys are the group names and values are subsets
of the :class:`~pandera.schema_components.Column` series.
Specifying ``groupby`` as a column name, list of column names, or
callable changes the expected signature of the :class:`~pandera.checks.Check` function
argument to ``dict[Any|tuple[Any], Series] -> bool|Series[bool]`` where
the dict keys are the discrete keys in the ``groupby`` columns.
.. testcode:: column_check_groups
import pandas as pd
import pandera as pa
from pandera import Column, Check, DataFrameSchema
schema = DataFrameSchema({
"height_in_feet": Column(
pa.Float, [
# groupby as a single column
Check(lambda g: g[False].mean() > 6,
groupby="age_less_than_20"),
# define multiple groupby columns
Check(lambda g: g[(True, "F")].sum() == 9.1,
groupby=["age_less_than_20", "sex"]),
# groupby as a callable with signature:
# (DataFrame) -> DataFrameGroupBy
Check(lambda g: g[(False, "M")].median() == 6.75,
groupby=lambda df: (
df
.assign(age_less_than_15=lambda d: d["age"] < 15)
.groupby(["age_less_than_15", "sex"]))),
]),
"age": Column(pa.Int, Check(lambda s: s > 0)),
"age_less_than_20": Column(pa.Bool),
"sex": Column(pa.String, Check(lambda s: s.isin(["M", "F"])))
})
df = (
pd.DataFrame({
"height_in_feet": [6.5, 7, 6.1, 5.1, 4],
"age": [25, 30, 21, 18, 13],
"sex": ["M", "M", "F", "F", "F"]
})
.assign(age_less_than_20=lambda x: x["age"] < 20)
)
schema.validate(df)
In the above example we define a :class:`~pandera.schemas.DataFrameSchema` with column
checks for ``height_in_feet`` using a single column, multiple columns, and a
more complex groupby function that creates a new column
``age_less_than_15`` on the fly.
Wide Checks
-----------
``pandera`` is primarily designed to operate on long-form data (commonly known
as `tidy data <https://vita.had.co.nz/papers/tidy-data.pdf>`_), where each row
is an observation and each column is an attribute associated with an
observation.
However, ``pandera`` also supports checks on wide-form data to operate across
columns in a ``DataFrame``.
For example, if you want to make assertions about ``height`` across two groups,
the tidy dataset and schema might look like this:
.. testcode:: wide_checks
import pandas as pd
import pandera as pa
from pandera import DataFrameSchema, Column, Check
df = pd.DataFrame({
"height": [5.6, 6.4, 4.0, 7.1],
"group": ["A", "B", "A", "B"],
})
schema = DataFrameSchema({
"height": Column(
pa.Float,
Check(lambda g: g["A"].mean() < g["B"].mean(), groupby="group")
),
"group": Column(pa.String)
})
schema.validate(df)
The equivalent wide-form schema would look like this:
.. testcode:: wide_checks
df = pd.DataFrame({
"height_A": [5.6, 4.0],
"height_B": [6.4, 7.1],
})
schema = DataFrameSchema(
columns={
"height_A": Column(pa.Float),
"height_B": Column(pa.Float),
},
# define checks at the DataFrameSchema-level
checks=Check(lambda df: df["height_A"].mean() < df["height_B"].mean())
)
schema.validate(df)
<file_sep><div align="left"><img src="https://raw.githubusercontent.com/pandera-dev/pandera/master/docs/source/_static/pandera-logo.png" width="140"></div>
# Pandera
A flexible and expressive [pandas](http://pandas.pydata.org) validation library.
<br>
[![Build Status](https://travis-ci.org/pandera-dev/pandera.svg?branch=master)](https://travis-ci.org/pandera-dev/pandera)
[![PyPI version shields.io](https://img.shields.io/pypi/v/pandera.svg)](https://pypi.org/project/pandera/)
[![PyPI license](https://img.shields.io/pypi/l/pandera.svg)](https://pypi.python.org/pypi/)
[![pyOpenSci](https://tinyurl.com/y22nb8up)](https://github.com/pyOpenSci/software-review/issues/12)
[![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active)
[![Documentation Status](https://readthedocs.org/projects/pandera/badge/?version=latest)](https://pandera.readthedocs.io/en/latest/?badge=latest)
[![codecov](https://codecov.io/gh/pandera-dev/pandera/branch/master/graph/badge.svg)](https://codecov.io/gh/pandera-dev/pandera)
[![PyPI pyversions](https://img.shields.io/pypi/pyversions/pandera.svg)](https://pypi.python.org/pypi/pandera/)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3385266.svg)](https://doi.org/10.5281/zenodo.3385266)
[![asv](http://img.shields.io/badge/benchmarked%20by-asv-green.svg?style=flat)](https://pandera-dev.github.io/pandera-asv-logs/)
`pandas` data structures contain information that `pandera` explicitly
validates at runtime. This is useful in production-critical or reproducible research
settings. `pandera` enables users to:
1. Check the types and properties of columns in a `DataFrame` or values in
a `Series`.
1. Perform more complex statistical validation like hypothesis testing.
1. Seamlessly integrate with existing data analysis/processing pipelines
via function decorators.
`pandera` provides a flexible and expressive API for performing data validation
on tidy (long-form) and wide data to make data processing pipelines more
readable and robust.
## Documentation
The official documentation is hosted on ReadTheDocs: https://pandera.readthedocs.io
## Install
Using pip:
```
pip install pandera
```
Using conda:
```
conda install -c conda-forge pandera
```
## Example Usage
### `DataFrameSchema`
```python
import pandas as pd
import pandera as pa
from pandera import Column, DataFrameSchema, Check, check_output
# validate columns
schema = DataFrameSchema({
# the check function expects a series argument and should output a boolean
# or a boolean Series.
"column1": Column(pa.Int, Check(lambda s: s <= 10)),
"column2": Column(pa.Float, Check(lambda s: s < -1.2)),
# you can provide a list of validators
"column3": Column(pa.String, [
Check(lambda s: s.str.startswith("value_")),
Check(lambda s: s.str.split("_", expand=True).shape[1] == 2)
]),
})
df = pd.DataFrame({
"column1": [1, 4, 0, 10, 9],
"column2": [-1.3, -1.4, -2.9, -10.1, -20.4],
"column3": ["value_1", "value_2", "value_3", "value_2", "value_1"]
})
validated_df = schema.validate(df)
print(validated_df)
# column1 column2 column3
# 0 1 -1.3 value_1
# 1 4 -1.4 value_2
# 2 0 -2.9 value_3
# 3 10 -10.1 value_2
# 4 9 -20.4 value_1
# If you have an existing data pipeline that uses pandas data structures, you can use the check_input and check_output decorators to check function arguments or returned variables from existing functions.
@check_output(schema)
def custom_function(df):
return df
```
## Development Installation
```
git clone https://github.com/pandera-dev/pandera.git
cd pandera
pip install -r requirements-dev.txt
pip install -e .
```
## Tests
```
pip install pytest
pytest tests
```
## Contributing to pandera [![GitHub contributors](https://img.shields.io/github/contributors/pandera-dev/pandera.svg)](https://github.com/pandera-dev/pandera/graphs/contributors)
All contributions, bug reports, bug fixes, documentation improvements, enhancements and ideas are welcome.
A detailed overview on how to contribute can be found in the [contributing guide](https://github.com/pandera-dev/pandera/blob/master/.github/CONTRIBUTING.md) on GitHub.
## Issues
Go [here](https://github.com/pandera-dev/pandera-dev/issues) to submit feature
requests or bugfixes.
## Other Data Validation Libraries
Here are a few other alternatives for validating Python data structures.
**Generic Python object data validation**
- [voloptuous](https://github.com/alecthomas/voluptuous)
- [schema](https://github.com/keleshev/schema)
**`pandas`-specific data validation**
- [opulent-pandas](https://github.com/danielvdende/opulent-pandas)
- [PandasSchema](https://github.com/TMiguelT/PandasSchema)
- [pandas-validator](https://github.com/c-data/pandas-validator)
- [table_enforcer](https://github.com/xguse/table_enforcer)
**Other tools that include data validation**
- [great_expectations](https://github.com/great-expectations/great_expectations)
## Why `pandera`?
- `pandas`-centric data types, column nullability, and uniqueness are
first-class concepts.
- `check_input` and `check_output` decorators enable seamless integration with
existing code.
- `Check`s provide flexibility and performance by providing access to `pandas`
API by design.
- `Hypothesis` class provides a tidy-first interface for statistical hypothesis
testing.
- `Check`s and `Hypothesis` objects support both tidy and wide data validation.
- Comprehensive documentation on key functionality.
### Citation Information
```
@misc{niels_bantilan_2019_3385266,
author = {<NAME> and
<NAME> and
<NAME> and
chr1st1ank},
title = {pandera-dev/pandera: 0.2.0 pre-release 1},
month = sep,
year = 2019,
doi = {10.5281/zenodo.3385266},
url = {https://doi.org/10.5281/zenodo.3385266}
}
```
<file_sep>#!/bin/sh
pip install schema
$PYTHON setup.py install
<file_sep>.. pandera package index documentation toctree
API
===
pandera.schemas
---------------
.. automodule:: pandera.schemas
:members:
:undoc-members:
:show-inheritance:
pandera.schema_components
-------------------------
.. automodule:: pandera.schema_components
:members:
:undoc-members:
:show-inheritance:
pandera.checks
--------------
.. automodule:: pandera.checks
:members:
:undoc-members:
:show-inheritance:
pandera.hypotheses
------------------
.. automodule:: pandera.hypotheses
:members:
:undoc-members:
:show-inheritance:
pandera.decorators
------------------
.. automodule:: pandera.decorators
:members:
:undoc-members:
:show-inheritance:
pandera.dtypes
--------------
.. automodule:: pandera.dtypes
:members:
:undoc-members:
:show-inheritance:
pandera.errors
--------------
.. automodule:: pandera.errors
:members:
:undoc-members:
:show-inheritance:
| 111f7c03c384def794f1de880883a550b3a0b798 | [
"reStructuredText",
"Markdown",
"Makefile",
"Python",
"Shell"
] | 10 | Python | chr1st1ank/pandera | b71d0eb39ddcaba07666b91324db58c8ffa9b5ef | e2fd24ce7fa02cf393645eb41b0b299944fa24a9 | |
refs/heads/master | <repo_name>Yujiao001/demo<file_sep>/src/com/cn/leecode/InsertInterval.java
import java.util.ArrayList;
/*
* Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
* You may assume that the intervals were initially sorted according to their start times.
* Example 1:
* Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
* Example 2:
* Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
* This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
*/
/**
* Definition for an interval.
* public class Interval {
* int start;
* int end;
* Interval() { start = 0; end = 0; }
* Interval(int s, int e) { start = s; end = e; }
* }
*/
public class InsertInterval {
public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
int left = -1, right = -1;
boolean leftIn = false, rightIn = false;
for(int i = 0; i < intervals.size(); i++) {
if(newInterval.start >= intervals.get(i).start) {
left = i;
leftIn = (newInterval.start <= intervals.get(left).end) ? true : false;
}
if(newInterval.end >= intervals.get(i).start) {
right = i;
rightIn = (newInterval.end <= intervals.get(right).end) ? true : false;
}
}
if(left == right) {
if(leftIn && !rightIn)
intervals.get(right).end = newInterval.end;
if(!leftIn && !rightIn)
intervals.add(left + 1, newInterval);
} else {
intervals.get(right).start = leftIn ? intervals.get(left).start : newInterval.start;
if(!rightIn)
intervals.get(right).end = newInterval.end;
for(int i = right - 1; i >= left + 1; i--) {
intervals.remove(i);
}
if(leftIn)
intervals.remove(left);
}
return intervals;
}
}
<file_sep>/src/com/cn/leecode/AddBinary.java
package com.cn.leecode;
/*
* Given two binary strings, return their sum (also a binary string).
* For example,
* a = "11"
* b = "1"
* Return "100".
*/
public class AddBinary {
public String addBinary(String a, String b) {
int len = Math.max(a.length(), b.length());
String res = "";
int carry = 0;
for (int i = 0; i < len; i++) {
int ca = i < a.length() ? a.charAt(a.length() - i - 1) - '0' : 0;
int cb = i < b.length() ? b.charAt(b.length() - i - 1) - '0' : 0;
res = (ca + cb + carry) % 2 + res;
carry = (ca + cb + carry) / 2;
}
if (carry > 0)
res = carry + res;
return res;
}
}
<file_sep>/src/com/co/sort/Removal0730.java
package com.co.sort;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
/*
* 去重排序,初步理解与运用。
*/
public class Removal0730 {
public static void main(String[] args) {
removal();
}
public static void removal(){
int arr[] ={0,98,6,5,1,98,6,896,896,896,0,5,1};
//Set的特性是没有重复元素
//TreeSet提供自动排序功能
Set<Integer> set =new TreeSet<Integer>(new MyComparator());
for(int i : arr){
set.add(i);
}
/*Iterator<Integer> iter = set.iterator();
while(iter.hasNext()){
int result = (int) iter.next();
System.out.print(result + " ");
}*/
for(Iterator<Integer> iter =set.iterator();iter.hasNext();){
System.out.print(iter.next() + " ");
}
}
}
class MyComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);//降序排列
}
}
<file_sep>/src/com/co/sort/SetTest.java
package com.co.sort;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class SetTest {
public static void main(String[] args) {
Set<Person> set = new TreeSet<Person>(new PersonComparator());
Person p1 = new Person(10);
Person p2 = new Person(20);
Person p3 = new Person(30);
Person p4 = new Person(40);
set.add(p1);
set.add(p2);
set.add(p3);
set.add(p4);
for(Iterator<Person> iterator = set.iterator();iterator.hasNext();){
System.out.print(iterator.next().score+" ");
}
}
}
class Person{
int score;
public Person(int score){
this.score = score;
}
public String toString(){
return String.valueOf(this.score);
}
}
class PersonComparator implements Comparator<Person>{
@Override
public int compare(Person o1, Person o2) {
return o1.score - o2.score;
}
}
<file_sep>/src/com/cn/leecode/BinaryTreeInorderTraversal.java
package com.cn.leecode;
import java.util.ArrayList;
import java.util.Stack;
import javax.swing.tree.TreeNode;
/*
* Given a binary tree, return the inorder traversal of its nodes' values.
* For example:
* Given binary tree {1,#,2,3},
* 1
* \
* 2
* /
* 3
* return [1,3,2].
* Note: Recursive solution is trivial, could you do it iteratively?
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BinaryTreeInorderTraversal {
/************************ updated 2013/11/30 ************************/
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (root != null) {
result.addAll(inorderTraversal(root.left));
result.add(root.val);
result.addAll(inorderTraversal(root.right));
}
return result;
}
/**************************************************************/
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
TreeNode cur = root;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
cur = cur.left;
} else {
cur = stack.pop();
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
/**************************************************************/
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
TreeNode cur = root;
while(cur != null) {
if(cur.left != null) {
TreeNode prev = cur.left;
while(prev.right != null && prev.right != cur)
prev = prev.right;
if(prev.right == cur) {
result.add(cur.val);
cur = cur.right;
prev.right = null;
} else {
prev.right = cur;
cur = cur.left;
}
} else {
result.add(cur.val);
cur = cur.right;
}
}
return result;
}
}
<file_sep>/src/com/co/sort/QuickSort0729.java
/**
*
*/
package com.co.sort;
public class QuickSort0729 {
public static void main(String[] args) {
int[] target = {22,45,12,1,5,7,98,34,678,321,1,4,6,9,0,5,124};
QuickSort(target,0,target.length-1);
for(int i = 0;i< target.length;i++){
System.out.print(target[i] + " ");
}
}
static void QuickSort(int[] arr,int left,int right){
int pivot =partion(arr,left,right);
if(left<pivot-1) QuickSort(arr,left,pivot-1);
if(right>pivot) QuickSort(arr,pivot,right);
}
static int partion(int[] arr,int left,int right){
int pivot = arr[(left+right)/2];
while(left<=right){
while(arr[left]<pivot) left++;
while(arr[right]>pivot) right--;
if(left<=right){
swap(arr,left,right);
left++;
right--;
}
}
return left;
}
static void swap(int[] arr,int left,int right){
int temp = arr[left];
arr[left] =arr[right];
arr[right] = temp;
}
}<file_sep>/src/com/cn/leecode/ImplementstrStr.java
package com.cn.leecode;
/*
* Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
*/
public class ImplementstrStr {
public String strStr(String haystack, String needle) {
if(needle.length() == 0 || haystack.equals(needle))
return haystack;
int i = 0, j = 0;
for(; i <= haystack.length() - needle.length() && j < needle.length(); i++) {
if(haystack.charAt(i) == needle.charAt(0)) {
for(; j < needle.length(); j++) {
if(haystack.charAt(i + j) != needle.charAt(j)) {
j = 0;
break;
}
}
}
}
return j == needle.length() ? haystack.substring(i - 1) : null;
}
}
| ddb470c3bcf37b6249cd9cf0be07cba5e4bab22e | [
"Java"
] | 7 | Java | Yujiao001/demo | e2bb2a87c847fa3dbb4d49666a347e6e9b704d6c | 741e3cccb60ae59e8e08400c387a843d8b341d9a | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using Xunit;
namespace entra21_tests
{
public class ExerciseTest
{
[Fact]
public void Should_return_5050()
{
// BDD - Behavior Driven Design
// Dado, Quando, Deve
//dado- setup
var exercises = new Exercises();
//Ação - Quando
var result = exercises.Exercise2();
Assert.Equal(5050, result);
}
[Fact]
public void Should_return_numbers_from_1_to_200()
{
var exercises = new Exercises();
var result = exercises.Exercise3();
var expectedOutput = new int[]
{
1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,139,141,143,145,147,149,151,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,183,185,187,189,191,193,195,197,199
};
for (int i = 0; i < 100; i++)
{
Assert.Equal(expectedOutput[i], result[i]);
}
}
[Fact]
public void Should_return_age_average()
{
var exercises = new Exercises();
var Mylist = new List<int>(){5,15,40};
double result = exercises.Exercise4(Mylist);
Assert.Equal(20, result);
}
[Fact]
public void Should_Return_An_Percentage_Women_Between_18_and_35_Years()
{
//Given
var exercises = new Exercises();
var womensAges = new int[5]
{
30,22,25,13,15
};
var result = exercises.Exercise5(womensAges);
Assert.Equal(60, result);
}
[Theory]
[InlineData(10,6,2,2190)]
[InlineData(20,4.90,44,78694)]
public void Should_Return_Money_Spent_With_Cigarretes(double cigarettesPerDay,double walletPrice, double years, double quantity)
{
var exercises = new Exercises();
var result = exercises.Exercise7(cigarettesPerDay, walletPrice, years);
Assert.Equal(quantity, result);
}
[Theory]
[InlineData(6, new int[10]{6, 12, 18, 24, 30, 36, 42, 48, 54, 60})]
[InlineData(5, new int[10]{5, 10, 15, 20, 25, 30, 35, 40, 45, 50})]
public void should_return_the_input_multiplied_by_1_to_10(int number, int[] expectedResult)
{
// Dado / Setup
var exercises = new Exercises();
// Quando / Ação
var result = exercises.Exercise17(number);
// Deve / Asserções
Assert.Equal(result, expectedResult);
}
[Fact]
public void should_not_create_candidates_when_password_is_incorrect()
{
var exercises = new Exercises();
var candidates = new List <string> {"João"};
var created = exercises.CreateCandidate(candidates, "Incorrect");
Assert.Null(exercises.Candidates);
Assert.False(created);
}
[Fact]
public void should_create_candidates_when_password_is_correct()
{
//Given
var exercises = new Exercises();
var candidateJose = "Jose";
var candidates = new List <string> {candidateJose};
//When
var created = exercises.CreateCandidate(candidates, "Pa$$w0rd");
//Then
Assert.True(created);
Assert.Equal(1, exercises.Candidates.Count);
Assert.Equal(candidateJose, exercises.Candidates[0].name);
}
[Fact]
public void should_return_same_candidates()
{
//Given
var exercises = new Exercises();
string Jose = "Jose";
string Ana = "Ana";
var candidates = new List <string> {Jose, Ana};
exercises.CreateCandidate(candidates, "Pa$$w0rd");
//When
var candidateJose = exercises.GetCandidateIdByName(Jose);
var candidateAna = exercises.GetCandidateIdByName(Ana);
Assert.NotEqual(candidateAna, candidateJose);
}
[Fact]
public void should_vote_twice_in_candidate_Jose()
{
// Dado / Setup
// OBJETO exercises
var exercises = new Exercises();
string Jose = "Jose";
string ana = "Ana";
var candidates = new List<string>{Jose, ana};
exercises.CreateCandidate(candidates, "Pa$$w0rd");
var joseId = exercises.GetCandidateIdByName(Jose);
var anaId = exercises.GetCandidateIdByName(ana);
// Quando / Ação
// Estamos acessando o MÉTODO ShowMenu do OBJETO exercises
exercises.Vote(joseId);
exercises.Vote(joseId);
// Deve / Asserções
var candidateJose = exercises.Candidates.Find(x => x.id == joseId);
var candidateAna = exercises.Candidates.Find(x => x.id == anaId);
Assert.Equal(2, candidateJose.votes);
Assert.Equal(0, candidateAna.votes);
}
[Fact]
public void should_return_Ana_as_winner_when_only_Ana_receives_votes()
{
// Dado / Setup
// OBJETO exercises
var exercises = new Exercises();
string Jose = "Jose";
string ana = "Ana";
var candidates = new List<string>{Jose, ana};
exercises.CreateCandidate(candidates, "Pa$$w0rd");
var anaId = exercises.GetCandidateIdByName(ana);
// Quando / Ação
// Estamos acessando o MÉTODO ShowMenu do OBJETO exercises
exercises.Vote(anaId);
exercises.Vote(anaId);
var winners = exercises.GetWinners();
// Deve / Asserções
Assert.Equal(1, winners.Count);
Assert.Equal(anaId, winners[0].id);
Assert.Equal(2, winners[0].votes);
}
[Fact]
public void should_return_both_candidates_when_occurs_draw()
{
// Dado / Setup
// OBJETO exercises
var exercises = new Exercises();
string Jose = "Jose";
string ana = "Ana";
var candidates = new List<string>{Jose, ana};
exercises.CreateCandidate(candidates, "Pa$$w0rd");
var joseId = exercises.GetCandidateIdByName(Jose);
var anaId = exercises.GetCandidateIdByName(ana);
// Quando / Ação
// Estamos acessando o MÉTODO ShowMenu do OBJETO exercises
exercises.Vote(anaId);
exercises.Vote(joseId);
var winners = exercises.GetWinners();
// Deve / Asserções
var candidateJose = winners.Find(x => x.id == joseId);
var candidateAna = winners.Find(x => x.id == anaId);
Assert.Equal(1, candidateJose.votes);
Assert.Equal(1, candidateAna.votes);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace entra21_tests
{
class Exercises
{
public int Exercise2()
{
var sum = 0;
for (int i = 1; i < 101; i++)
{
//sum = 1
//sum = 3
sum += i;
}
return sum;
}
public int[] Exercise3()
{
var numbers = new int[100];
var count = 1;
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = count;
count += 2;
}
return numbers;
}
public double Exercise4(List<int> ages)
{
double sum = 0.0;
var a = ages.Count;
foreach (var item in ages)
{
sum += item;
}
var average = sum / a;
return average;
}
public double Exercise5(int[] ages)
{
var percent = 0.0;
foreach (var womensAge in ages)
{
percent = (womensAge > 17 && womensAge < 36) ? percent += 1 : percent;
}
return Math.Floor((percent/ages.Length)*100);
}
public double Exercise7(double cigarettesPerDay, double walletPrice, double years)
{
const int walletCigarettes = 20;
var cigarettePrice = walletPrice / walletCigarettes;
var daysSmoking = years * 365;
return Math.Floor (daysSmoking * cigarettesPerDay * cigarettePrice);
}
public IEnumerable<int> Exercise17(int number)
{
// Imprimir a tabuada de qualquer número fornecido pelo usuário.
// DADO que a aplicação esteja pronta, QUANDO o usuário informar um número
// DEVE retornar a tabuada de 1 a 10
var multiplicationTable = new List<int>(){
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
// é tipo um foreach,cada vez que
// \/passa o item(que começa na posição 0)sobe 1 posição.
// \/ E NAO ALTERA A LISTA (multiplicationTable)
return multiplicationTable.Select(item => item * number);
}
public List <(Guid id, string name, int votes)> Candidates {get ; set;}
public bool CreateCandidate(List<string> candidatesNames,string password)
{
if(password == "<PASSWORD>")
{
Candidates = candidatesNames.Select(item => {
return (Guid.NewGuid(), item, 0);
}).ToList();
return true;
}
return false;
}
public Guid GetCandidateIdByName(string name)
{
return Candidates.First(x => x.name == name).id;
}
public void Vote(Guid id)
{
Candidates = Candidates.Select(item => {
return item.id == id ? (item.id, item.name, item.votes + 1) : item;
}).ToList();
}
public List<(Guid id, string name, int votes)> GetWinners()
{
var winners = new List<(Guid id, string name, int votes)>{Candidates[0]};
for (int i = 1; i < Candidates.Count; i++)
{
if (Candidates[i].votes > winners[0].votes)
{
winners.Clear();
winners.Add(Candidates[i]);
}
else if (Candidates[i].votes == winners[0].votes)
{
winners.Add(Candidates[i]);
}
}
return winners;
}
public List<(string cpf, string name)> CpfCandidates()
{
}
}
} | d1b6a459dbc2589cff45680d89fe78161cea6c1b | [
"C#"
] | 2 | C# | Silmar3347/entra21-tests | 96b23857719be61ddc00390af3b3976c6a9c0391 | d4a58fce603a0754adaed03fe557b00024793c1c | |
refs/heads/master | <file_sep>package com.excilys.formation.battleships.android.ui.ships;
import com.excilys.formation.battleships.ship.Submarine;
import java.util.HashMap;
import java.util.Map;
import battleships.formation.excilys.com.battleships.R;
/**
* Created by tiberiodarferreira on 06/10/2016.
*/
public class DrawableSubmarine extends Submarine implements DrawableShip {
public DrawableSubmarine(Orientation orientation){
super(orientation);
}
public DrawableSubmarine(){
super(Orientation.NORTH);
}
static final Map<Orientation, Integer> DRAWABLES = new HashMap<>();
static {
// The code inside here will be executed just once when the class is loaded
// So all the changes here are shared with the "brother" classes
DRAWABLES.put(Orientation.NORTH, R.drawable.submarine_s);
DRAWABLES.put(Orientation.SOUTH, R.drawable.submarine_n);
DRAWABLES.put(Orientation.WEST, R.drawable.submarine_w);
DRAWABLES.put(Orientation.EAST, R.drawable.submarine_e);
}
@Override
public int getDrawable() {
return DRAWABLES.get(this.getOrientation());
}
}
<file_sep>package com.excilys.formation.battleships.ship;
/**
* Created by tiberiodarferreira on 23/09/2016.
*/
public class Submarine extends AbstractShip {
public Submarine(){
super("", ShipType.SUBMARINE, null, 3);
}
public Submarine(Orientation orientation){
super("", ShipType.SUBMARINE, orientation, 3);
}
}
<file_sep>package com.excilys.formation.battleships;
import com.excilys.formation.battleships.ship.AbstractShip;
import com.excilys.formation.battleships.ship.ShipState;
import java.util.ArrayList;
import java.util.List;
/**
* Created by tiberiodarferreira on 16/09/2016.
*/
public class Board implements IBoard{
private int size;
private Boolean[][] frappes;
private ShipState[][] navire;
private String name;
private Board(String name, int size){
this.name = name;
if (size>20){
System.out.println("Tableau trop grand! Limit = 20");
}else{
this.size = size;
}
frappes = new Boolean[size][size];
navire = new ShipState[size][size];
for (int i = 0; i<size; i++){
for (int j = 0; j<size; j++){
navire[i][j] = new ShipState();
}
}
}
String getName(){
return name;
}
public Board(String name){
this(name, 10);
}
/**
Outputs the tables to the screen
*/
void printTableau(){
System.out.print("Navires:");
for (int i=0; i<1 + 2*size; i++) {
System.out.print(" ");
}
System.out.println("Frappes:");
System.out.print("\t");
for (char ch = 'A'; ch<(size+'A'); ch++){
System.out.print( " " + ch);
}
System.out.print("\t\t");
for (char ch = 'A'; ch<(size+'A'); ch++){
System.out.print( " " + ch);
}
System.out.println();
for (int i = 0; i < size; i++){
for (int un_deux=0; un_deux<2; un_deux++) { // 0 = navire 1 = frappes
System.out.print(i);
System.out.print('\t');
for (int i_nested1 = 0; i_nested1 < size; i_nested1++) {
if (un_deux == 1) {
if (frappes[i_nested1][i] == null) {
System.out.print(" .");
} else if(!frappes[i_nested1][i]) {
System.out.print(ColorUtil.colorize(" X", ColorUtil.Color.WHITE));
} else if(frappes[i_nested1][i]) {
System.out.print(ColorUtil.colorize(" X", ColorUtil.Color.RED));
}
}else{
if(navire[i_nested1][i].isStruck()) {
System.out.print(ColorUtil.colorize(" " + navire[i_nested1][i].getShipAsChar(), ColorUtil.Color.RED));
}else {
System.out.print(" " + navire[i_nested1][i].getShipAsChar());
}
}
}
System.out.print('\t');
}
System.out.println();
}
}
public int getSize() {
return size;
}
@Override
public boolean hasShip(int x, int y) {
return (navire[x][y].isShip());
}
/**
@param hit True if hit something, false if missed
@param x The coordinate x of the hit
@param y The coordinate y of the hit
*/
@Override
public void setHit(boolean hit, int x, int y) {
if (!isInsideGrid(x, y)){
System.out.println("Invalid location: x = " + x + " y= " + y);
return;
}
frappes[x][y] = hit;
}
/**
@param x The coordinate x of the hit
@param y The coordinate y of the hit
@return True if there is a hit (!=miss) in the coordinates, false if there is not
*/
@Override
public Boolean getHit(int x, int y) {
if (!isInsideGrid(x, y)){
System.out.println("Invalid location: x = " + x + " y= " + y);
return false;
}
return frappes[x][y];
}
/**
@param x The coordinate x of the hit
@param y The coordinate y of the hit
@return A Hit representing what was hit at (x, y)
*/
public Hit sendHit(int x, int y){
if (!isInsideGrid(x, y)){
System.out.println("Invalid location: x = " + x + " y= " + y);
return null;
}
navire[x][y].addStrike();
if(!navire[x][y].isShip()){
return Hit.fromInt(-1);
}else if(navire[x][y].isSunk()) {
switch (navire[x][y].getShip().getShipType()) {
case BATTLESHIP:
return Hit.fromInt(4);
case DESTROYER:
return Hit.fromInt(2);
case SUBMARINE:
return Hit.fromInt(3);
case CARRIER:
return Hit.fromInt(5);
default:
System.out.println("Holy intervention is preventing this program from working properly.");
return null;
}
}else{
return Hit.fromInt(-2);
}
}
/**
@param ship The ship to be put
@param x The coordinate x where to put the ship
@param y The coordinate y where to put the ship
*/
@Override
public int putShip(AbstractShip ship, int x, int y) {
if (!isInsideGrid(x, y)){
System.out.println("Invalid location: x = " + x + " y= " + y);
return -1;
}
assert ship.getOrientation() != null : "Ship with null orientation being added!";
int x_temp = x;
int y_temp = y;
List<AbstractShip.Location> shipLocation = new ArrayList<>();
for (int i=0; i < ship.getLength(); i++) {
AbstractShip.Location Loc = new AbstractShip.Location(x_temp, y_temp);
shipLocation.add(Loc);
if (ship.getOrientation() == AbstractShip.Orientation.EAST) {
x_temp += 1;
} else if (ship.getOrientation() == AbstractShip.Orientation.WEST) {
x_temp -= 1;
} else if (ship.getOrientation() == AbstractShip.Orientation.NORTH) {
y_temp -= 1;
} else if (ship.getOrientation() == AbstractShip.Orientation.SOUTH) {
y_temp += 1;
}
}
for (AbstractShip.Location Loc : shipLocation){
if (!isInsideGrid(Loc.getX(), Loc.getY())){
System.out.println("This puts the ship outside the board!");
return -1;
}
if(hasShip(Loc.getX(), Loc.getY())){
System.out.println("Cannot put ship there, there is already one at X = " + Loc.getX() + " Y = " + Loc.getY());
return -1;
}
}
for (AbstractShip.Location Loc : shipLocation){
System.out.println("X = " + Loc.getX() + " Y= " + Loc.getY());
navire[Loc.getX()][Loc.getY()] = new ShipState(ship);
}
printTableau();
return 1;
}
/**
@param x Coordinate x
@param y Coordinate y
@return True if the coordinates are of a position already hit
*/
public boolean alreadyHit(int x, int y){
if (!isInsideGrid(x, y)){
System.out.println("Invalid location: x = " + x + " y= " + y);
return false;
}
return navire[x][y].isStruck();
}
/**
@param x Coordinate x
@param y Coordinate y
@return True if the coordinates are inside the game table, false otherwise
*/
private boolean isInsideGrid(int x, int y){
return !((x < 0 || y < 0) || ((x > size - 1 || y > size - 1)));
}
}
<file_sep>package com.excilys.formation.battleships.ship;
/**
* Created by tiberiodarferreira on 23/09/2016.
*/
public class Destroyer extends AbstractShip {
public Destroyer(){
super("", ShipType.DESTROYER, null, 2);
}
public Destroyer(Orientation orientation){
super("", ShipType.DESTROYER, orientation, 2);
}
}
<file_sep>package com.excilys.formation.battleships.android.ui.ships;
/**
* Just an interface to make sure all ships can be drawn on the screen
*/
public interface DrawableShip {
int getDrawable();
}
<file_sep>package com.excilys.formation.battleships.ship;
/**
* Created by tiberiodarferreira on 23/09/2016.
*/
public class Carrier extends AbstractShip {
public Carrier(){
super("", ShipType.CARRIER, null, 5);
}
public Carrier(Orientation orientation){
super("", ShipType.CARRIER, orientation, 5);
}
}
<file_sep>package com.excilys.formation.battleships.ship;
/**
* Created by tiberiodarferreira on 23/09/2016.
*/
public class Battleship extends AbstractShip {
public Battleship(){
super("", ShipType.BATTLESHIP, null, 4);
}
public Battleship(Orientation orientation){
super("", ShipType.BATTLESHIP, orientation, 4);
}
}
<file_sep>package com.excilys.formation.battleships;
import com.excilys.formation.battleships.ship.AbstractShip;
import com.excilys.formation.battleships.Board;
import java.io.Serializable;
import java.util.List;
public class Player {
protected Board board;
private Board opponentBoard;
public int destroyedCount;
protected AbstractShip[] ships;
public boolean lose;
private String name;
public Player(String name, Board board, Board opponentBoard, List<AbstractShip> ships) {
this.name = name;
this.board = board;
this.ships = ships.toArray(new AbstractShip[0]);
this.opponentBoard = opponentBoard;
}
public String getName(){
return this.name;
}
/**
* Read keyboard input to get ships coordinates. Place ships on given coordenates.
* Attempts to put the ships in pos x y
* @param x the x position
* @param y the y position
* Is not used in this Android version
*/
public void putShips(int x, int y) {
int i = 0;
boolean done = false;
do {
AbstractShip s = ships[i];
System.out.println("Place your " + s.getLabel());
InputHelper.ShipInput res = InputHelper.readShipInput();
AbstractShip.Orientation orientation;
switch (res.orientation) {
case "n":
orientation = AbstractShip.Orientation.NORTH;
break;
case "s":
orientation = AbstractShip.Orientation.SOUTH;
break;
case "e":
orientation = AbstractShip.Orientation.EAST;
break;
case "o":
orientation = AbstractShip.Orientation.WEST;
break;
default:
System.out.println("Not a valid orientation");
return;
}
s.setOrientation(orientation);
try {
board.putShip(s, res.x, res.y);
++i;
done = i == ships.length;
} catch(Exception e) {
System.err.println("Impossible de placer le navire a cette position");
System.out.println(e);
}
board.printTableau();
} while (!done);
}
/**
* Asks the players for coordinates and sends an Hit on opponents table on those coordinates
* @param coords Variable which should be an int[2] and which will be populated with the
* coordinates of where the shot was sent
* @return hit which contains the information about the success of the shot
*/
public Hit sendHit(int[] coords) {
boolean done = false;
Hit hit = null;
do {
InputHelper.CoordInput hitInput = InputHelper.readCoordInput();
hit = opponentBoard.sendHit(hitInput.x, hitInput.y);
coords[0] = hitInput.x;
coords[1] = hitInput.y;
if (hit != null) {
done = true;
}
} while (!done);
return hit;
}
public AbstractShip[] getShips() {
return ships;
}
public void setShips(AbstractShip[] ships) {
this.ships = ships;
}
}<file_sep>package com.excilys.formation.battleships.ship;
/**
* Created by tiberiodarferreira on 23/09/2016.
*/
public class ShipState {
private AbstractShip ship;
private boolean struck = false;
public ShipState(AbstractShip ship){
this.ship = ship;
}
public ShipState(){
this.ship = null;
}
public boolean isShip(){
return !(ship==null);
}
public AbstractShip getShip(){
return ship;
}
public boolean isSunk(){
return ship.strikeCount==ship.getLength();
}
public boolean isStruck(){
return struck;
}
/**
Adds a strike to the ship.
It is used in order to track if the ship has sunk or not.
*/
public void addStrike(){
if(!struck) {
struck = true;
if (isShip()) {
ship.strikeCount++;
}
}
}
public String toString(){
if (ship!=null) {
return ship.getLabel().toString();
}else {
return ".";
}
}
/**
This is useful to populate the table representing the ships without having to convert a String to char each time
*/
public char getShipAsChar(){
if (ship==null) {
return '.';
}else {
return ship.getShipType().getAsChar();
}
}
}
<file_sep>package com.excilys.formation.battleships.android.ui;
import android.app.Application;
import android.content.Intent;
import com.excilys.formation.battleships.AIPlayer;
import com.excilys.formation.battleships.Board;
import com.excilys.formation.battleships.Player;
import com.excilys.formation.battleships.android.ui.ships.DrawableBattleship;
import com.excilys.formation.battleships.android.ui.ships.DrawableCarrier;
import com.excilys.formation.battleships.android.ui.ships.DrawableDestroyer;
import com.excilys.formation.battleships.android.ui.ships.DrawableSubmarine;
import com.excilys.formation.battleships.ship.AbstractShip;
import java.util.Arrays;
import java.util.List;
public class BattleShipsApplication extends Application {
/* ***
* Attributes
*/
// BoardController = Implements the visual part of the Board on top of the Board logic
private static BoardController mBoardcontroller;
// The opponent Board, at first it will just be an AI, but could be another player over network
private static Board mOpponentBoard;
// The game object itself created during the start of the application by the
// onCreate method
private static Game mGame;
// Stores the player's name
private String mPlayerName;
// Stores the the players
private static Player[] mPlayers;
public BoardController getBoardController(){
return mBoardcontroller;
}
static public Board getOpponentBoard(){
return mOpponentBoard;
}
@Override
public void onCreate() {
super.onCreate();
mGame = new Game();
}
public static Game getGame() {
return mGame;
}
public static BoardController getBoard() {
return mBoardcontroller;
}
public static Player[] getPlayers() {
return mPlayers;
}
/* ***
* Nested classes
*/
public class Game {
/* ***
* Attributes
*/
private AndroidPlayer mPlayer1;
private Player mPlayer2;
/* ***
* Methods
*/
public Game init(String playerName) {
mPlayerName = playerName;
Board board = new Board(playerName);
mBoardcontroller = new BoardController(board);
mOpponentBoard = new Board("IA");
// Android Player is the "regular player", but the putShips opens an Android Activity
// so the ships can be put using a nice interface
mPlayer1 = new AndroidPlayer(playerName, board, mOpponentBoard, createDefaultShips());
mPlayer2 = new AIPlayer(mOpponentBoard, board, createDefaultShips());
mPlayers = new Player[] {mPlayer1, mPlayer2};
// Show the putShips view and wait for the player to put it's ships.
mPlayer1.putShips();
return this;
}
private List<AbstractShip> createDefaultShips() {
AbstractShip[] ships;
ships = new AbstractShip[]{new DrawableDestroyer(), new DrawableSubmarine(), new DrawableSubmarine(), new DrawableBattleship(), new DrawableCarrier()};
return Arrays.asList(ships);
}
}
public class AndroidPlayer extends Player {
// Just a regular "Player" class apart from the putShips method which is overloaded
AndroidPlayer(String name, Board board, Board opponentBoard, List<AbstractShip> ships){
super(name, board, opponentBoard, ships);
}
void putShips() {
Intent intent = new Intent(getApplicationContext(), PutShipsActivity.class);
startActivity(intent);
}
}
}
| 9386cb6ead9ea4b5daff1b8ca7acffb2600d155a | [
"Java"
] | 10 | Java | tiberiusferreira/ASI11-TP-Android | 5fdd93f8ff1df429b5bc413184cf6f457fba6959 | 807396e456e15e12e9f365292744996a2b818c98 | |
refs/heads/master | <repo_name>Vivianraj/Crack_detection-using-Deep-learning-<file_sep>/app.py
#!/usr/bin/env python
# coding: utf-8
# In[28]:
from __future__ import division, print_function
import sys
import os
import glob
import re
import numpy as np
import cv2
import tensorflow as tf
# Keras
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.preprocessing import image
# Flask utils
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
# In[29]:
# Define a flask app
app = Flask(__name__)
# In[30]:
MODEL_PATH = 'D:/deploy/road_crack_new.h5'
# In[31]:
model = tf.keras.models.load_model(MODEL_PATH)
model._make_predict_function()
# In[32]:
def model_predict(img_path, model):
img = cv2.imread(os.path.join(img_path),0)
img_size = 224
th = 1
max_value = 255
blocksize = 79
constant = 2
img_f = cv2.bilateralFilter(img,9,75,75)
ret, o2 = cv2.threshold(img_f, th, max_value, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
x = cv2.resize(o2,(img_size,img_size))
x = x/255
x = np.array(x).reshape(-1,img_size,img_size,1)
preds = model.predict(x)
return preds
# In[33]:
@app.route('/', methods=['GET'])
def index():
# Main page
return render_template('index.html')
# In[37]:
@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = 'D:/deploy'
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
preds = model_predict(file_path, model)
negative = round(preds[0][0],5)
positive = round(preds[0][1],5)
if negative >= 0.5:
result = 'Negative - No crack found'
else:
result = 'Positive - Crack found'
return result
return None
# In[38]:
if __name__ == '__main__':
app.run(debug=True)
# In[ ]:
<file_sep>/requirements.txt
Flask==1.1.2
gunicorn==20.0.4
numpy>=1.18.3
pandas>=0.24.2
opencv-python==4.2.0.32
tensorflow==2.1.0
scipy==1.4.1
| 2e396009015afb284337e1fbff0300b941ef0479 | [
"Python",
"Text"
] | 2 | Python | Vivianraj/Crack_detection-using-Deep-learning- | 844a8795fe1a4f1df66d15a7b75a9535fdf4cadb | 6c5c385d846ea512952009b198cc705a0a41fab3 | |
refs/heads/master | <repo_name>ethiekx/nacl-3<file_sep>/ext/nacl/extconf.rb
require 'mkmf'
have_library "nacl"
create_makefile('nacl/nacl')
| 80e9f4341bcce832caea64bb2d47a7f7fac4e06b | [
"Ruby"
] | 1 | Ruby | ethiekx/nacl-3 | a41786d6478a29cf1731a9e73b7af209d910f917 | 53aabc843ffc61dace293f4c5ada99a10f4d0861 | |
refs/heads/master | <file_sep>//
// ViewController.swift
// Touch ID
//
// Created by <NAME> on 28/02/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import LocalAuthentication
class ViewController: UIViewController {
@IBOutlet weak var infoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if #available(iOS 9.0, *) {
//A partir de iOS 9
let authenticationContext = LAContext()
var error: NSError?
if authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
authenticationContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Posez votre doigt sur le capteur d'empreinte pour dévérouiller votre application", reply: { (success: Bool, error: Error?) in
if success {
//Empreinte OK
self.performSegue(withIdentifier: "mdp_ok", sender: self)
} else {
//L'utilisateur à annulé ou choisi de rentrer un mot de passe à la place
if let evaluateError = error as? NSError {
let code_erreur:Int = evaluateError.code
let msg_erreur:String = self.getInfoAvecCode(code: code_erreur)
self.infoLabel.text = msg_erreur
if( code_erreur == LAError.userFallback.rawValue ){
//L'utilisateur préfère rentrer son mot de passe
self.demanderMotDePasse()
}
}
}
})
} else {
//Si il n'y a pas pas de lecteur d'empreinte digitale
demanderMotDePasse()
}
} else {
//Si on est dans iOS inférieur à la version 9.0
demanderMotDePasse()
}
}
func demanderMotDePasse() {
infoLabel.text = "Entrez votre mot de passe"
//Faire quelque chose pour demander le mot de passe à la place
//Ce doit être votre propre systeme..
//...
}
//Optionel, juste pour mettre des message personalisés, traduisez-les :)
func getInfoAvecCode(code: Int) -> String {
var message = ""
/*
Si code = -9, afficher "Authentication was cancelled by application"
Si code = -1, afficher "The user failed to provide valid credentials"
...etc
*/
switch code {
case LAError.appCancel.rawValue://-9
message = "Authentication was cancelled by application"
case LAError.authenticationFailed.rawValue://-1
message = "The user failed to provide valid credentials"
case LAError.invalidContext.rawValue://-10
message = "The context is invalid"
case LAError.passcodeNotSet.rawValue://..etc
message = "Passcode is not set on the device"
case LAError.systemCancel.rawValue:
message = "Authentication was cancelled by the system"
case LAError.touchIDLockout.rawValue:
message = "Too many failed attempts."
case LAError.touchIDNotAvailable.rawValue:
message = "TouchID is not available on the device"
case LAError.userCancel.rawValue:
message = "The user did cancel"
case LAError.userFallback.rawValue:
//message = "The user chose to use the fallback"
message = "Entrez le mot de passe"
default:
message = "Did not find error code on LAError object"
}
return message
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>//
// ViewController.swift
// Touch ID
//
// Created by <NAME> on 28/02/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import LocalAuthentication
class ViewController: UIViewController {
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var motDePasse: UITextField!
var motDePasseTest:String = "12341234"
/* NSUserDefaults est capable de stoquer:
NSData, NSString, NSNumber, NSDate, NSArray, ou NSDictionary.
https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
*/
let maVariableIneffacable:UserDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let deverouillerParTouchID:Bool = maVariableIneffacable.bool(forKey: "deverouillerParTouchID") as Bool
if(deverouillerParTouchID) {
verifParEmpreinteDigitale()
}
//Sinon, l'authentification par mot de passe est proposé dans tous les cas
}
func verifParEmpreinteDigitale() {
if #available(iOS 9.0, *) {
//A partir de iOS 9
let myContext = LAContext()
let myLocalizedReasonString = "Posez votre doigt sur le capteur d'empreinte pour dévérouiller votre application"
var authError: NSError? = nil
if myContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
myContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: myLocalizedReasonString) { (success, evaluateError) in
if (success) {
//Empreinte OK
self.performSegue(withIdentifier: "mdp_ok", sender: self)
} else {
//L'utilisateur à annulé ou choisi de rentrer un mot de passe à la place
if let evaluateError = evaluateError as? NSError {
let code_erreur:Int = evaluateError.code
let msg_erreur:String = Fonctions.getInfoAvecCode(code: code_erreur)
self.infoLabel.text = msg_erreur
}
}
}
}
}
}
@IBAction func verifParMDP(_ sender: UIButton) {
if( motDePasse.text == motDePasseTest ){
self.performSegue(withIdentifier: "mdp_ok", sender: self)
} else {
infoLabel.text = "Mot de passe incorect"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
<file_sep>//
// ParametreViewController.swift
// Touch ID
//
// Created by <NAME> on 28/02/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
import LocalAuthentication
class ParametreViewController: UIViewController {
@IBOutlet weak var touchIdSwitch: UISwitch!
let maVariableIneffacable:UserDefaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
touchIdSwitch.addTarget(self, action: #selector(evenementSwitch(leSwitch:)), for: UIControlEvents.valueChanged)
let deverouillerParTouchID:Bool = maVariableIneffacable.bool(forKey: "deverouillerParTouchID") as Bool
if(deverouillerParTouchID) {
//Metre à ON quand l'utilisateur à déjà validé son empreinte et revient sur l'application
touchIdSwitch.setOn(true, animated: true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func evenementSwitch(leSwitch: UISwitch) {
if leSwitch.isOn {
verifEmpreinteDigitale()
} else {
self.maVariableIneffacable.set(false, forKey: "deverouillerParTouchID")
}
}
func verifEmpreinteDigitale() {
if #available(iOS 9.0, *) {
//A partir de iOS 9
let myContext = LAContext()
let myLocalizedReasonString = "Posez votre doigt sur le capteur d'empreinte pour confirmé"
var authError: NSError? = nil
if myContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
myContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: myLocalizedReasonString) { (success, evaluateError) in
if (success) {
//Empreinte OK
self.maVariableIneffacable.set(true, forKey: "deverouillerParTouchID")
} else {
//L'utilisateur a annulé
self.touchIdSwitch.setOn(false, animated: true)//Metre à OFF
self.alert("Impossible", "Impossible d'effectuer l'action")
}
}
} else {
alert("Introuvable", "Vous n'avez pas de lecteur d'empreinte digitale")
touchIdSwitch.setOn(false, animated: true)//Metre à OFF
}
} else {
alert("Introuvable", "Vous n'avez pas de lecteur d'empreinte digitale")
touchIdSwitch.setOn(false, animated: true)//Metre à OFF
}
}
func alert(_ titre: String, _ message: String) {
let alert = UIAlertController(title: titre, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default)
alert.addAction(okAction)
present(alert, animated: true)
}
}
<file_sep>//
// PrevisonsViewController.swift
// Meteo
//
// Created by <NAME> on 13/05/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class PrevisonsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var ville:String = ""
@IBOutlet weak var barre_haut: UINavigationBar!
@IBOutlet weak var tableView: UITableView!
var data = [Meteo]()
override func viewDidLoad() {
super.viewDidLoad()
barre_haut.topItem?.title = "Prévisons de \(ville)"
do {
let url = NSURL(string: "http://api.openweathermap.org/data/2.5/forecast?appid=79ab92ee7aba089ef7c6dbb6c96c9a54&units=metric&q=\(ville)");
let texte:NSString = try NSString(contentsOf: url! as URL, usedEncoding: nil)
let jsonData = texte.data(using: 4)
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: jsonData!) as? NSDictionary
if let jsonResult = jsonResult {
let list = jsonResult["list"]! as! NSArray
for meteo_ in list {
let meteo:NSDictionary = meteo_ as! NSDictionary
let dt = meteo["dt"]! as! Int
let main = meteo["main"]! as! NSDictionary
let weather_array = meteo["weather"]! as! NSArray
let weather = weather_array[0] as! NSDictionary
let id_condition:Int = weather["id"] as! Int
let temp = main["temp"] as! Double
self.data.append(Meteo(unix: dt, temp: temp, id_condition: id_condition))
}
}
} catch {
print("Erreur de conversion")
}
}
@IBAction func quitter(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
// MARK: - Table View
func numberOfSections(in tableView: UITableView) -> Int
{
//Nombre de section: Une seule
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
//Nombre de cellules à afficher:
return self.data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
//Customisation de notre cellule
let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cellule") as! CustomTableViewCell
let meteo:Meteo = self.data[indexPath.row]
cell.icone.image = UIImage(named: meteo.nom_image)
cell.degre.text = "\(meteo.temperature) °C"
cell.description_meteo.text = meteo.description
cell.date.text = meteo.date_string
return cell
}
}
<file_sep>//
// CustomTableViewCell.swift
// Meteo
//
// Created by <NAME> on 13/05/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var icone: UIImageView!
@IBOutlet weak var degre: UILabel!
@IBOutlet weak var description_meteo: UILabel!
@IBOutlet weak var date: UILabel!
}
<file_sep>//
// Meteo.swift
// Meteo
//
// Created by <NAME> on 13/05/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import Foundation
class Meteo {
var date_string:String = ""
var temperature:Double = 0.0
var description:String = ""
var nom_image:String = ""
init(unix:Int, temp:Double, id_condition:Int) {
traiter_date(unix: unix)
traiter_conditions(id: id_condition)
self.temperature = temp
}
private func traiter_date(unix:Int) {
let ns_date = NSDate(timeIntervalSince1970: TimeInterval(unix))
let date:Date = ns_date as Date
let date_formatter:DateFormatter = DateFormatter()
date_formatter.dateFormat = "dd MMM YYYY à HH:mm" //03 Mai 2017 à 09:00
self.date_string = date_formatter.string(from: date)+"H"
}
private func traiter_conditions(id:Int) {
switch id {
case 200...232:
self.nom_image = "11d.png"
self.description = "Orage"
case 300...321, 520...531:
self.nom_image = "09d.png"
self.description = "Pluie nuageuse"
case 500...504:
self.nom_image = "10d.png"
self.description = "Pluie ensoleillé"
case 511:
self.nom_image = "13d.png"
self.description = "Pluie verglaçante"
case 800:
self.nom_image = "01d.png"
self.description = "Ciel clair"
case 801...804:
self.nom_image = "03d.png"
self.description = "Nuageux"
default:
self.nom_image = "01d.png"
self.description = "Ciel clair"
}
}
}
<file_sep>//
// ViewController.swift
// Meteo
//
// Created by <NAME> on 13/05/2017.
// Copyright © 2017 <NAME>. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image_fond: UIImageView!
@IBOutlet weak var degre: UILabel!
@IBOutlet weak var icone: UIImageView!
@IBOutlet weak var description_meteo: UILabel!
@IBOutlet weak var ville: UITextField!
@IBOutlet weak var date: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
rechercher(ville: "Paris")
}
func rechercher(ville:String) {
do {
let url = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?appid=79ab92ee7aba089ef7c6dbb6c96c9a54&units=metric&q=\(ville)");
let texte:NSString = try NSString(contentsOf: url! as URL, usedEncoding: nil)
let jsonData = texte.data(using: 4)
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: jsonData!) as? NSDictionary
if let jsonResult = jsonResult {
let weather_array = jsonResult["weather"] as! NSArray
let weather = weather_array[0] as! NSDictionary
let main = jsonResult["main"] as! NSDictionary
let dt = jsonResult["dt"]! as! Int
let id_condition:Int = weather["id"] as! Int
let temp = main["temp"] as! Double
let meteo:Meteo = Meteo(unix: dt, temp: temp, id_condition: id_condition)
afficher(m: meteo)
}
} catch {
print("Erreur de conversion")
}
}
func afficher(m:Meteo) {
icone.image = UIImage(named: m.nom_image)
image_fond.image = UIImage(named: "f-"+m.nom_image)
degre.text = "\(m.temperature) °C"
description_meteo.text = m.description
date.text = "Dernière mise à jour le \(m.date_string)"
}
@IBAction func rechercher(_ sender: UIButton) {
rechercher(ville: ville.text!)
}
//MARK - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier=="aller_vers_previsons"){
let previsonsVC:PrevisonsViewController = segue.destination as! PrevisonsViewController
previsonsVC.ville = ville.text!
}
}
}
| d9eafc7dc666f80a75dcedfc8ea388e51d160063 | [
"Swift"
] | 7 | Swift | fkobon/Projets-iOS | 885857e17e7ac75cc3bcc64bcd2945a7fad4ce33 | 2aff3e8c31b4c20ebf686a00f0a80ce88f10c540 | |
refs/heads/master | <repo_name>adonskikh/FUSE<file_sep>/myfs.c
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include "fsfileops.h"
/** Get file attributes.
*
* Similar to stat(). The 'st_dev' and 'st_blksize' fields are
* ignored. The 'st_ino' field is ignored except if the 'use_ino'
* mount option is given.
*/
static int my_getattr(const char *path, struct stat *stbuf)
{
int res = 0;
//WriteToLog("getattr: ");
//WriteToLog(path);
memset(stbuf, 0, sizeof(struct stat));
long index = GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
/*char message[500];
sprintf(message, "GETATTR: index = %ld, path = %s, mode = %o, real size = %ld", index, path, n.di_mode, n.di_size);
WriteToLog(message);*/
if(n.di_size < 0)
return -ENOENT;
stbuf->st_ino = index; /* inode number */
stbuf->st_mode = n.di_mode; /* protection */
stbuf->st_nlink = n.di_nlink; /* number of hard links */
stbuf->st_uid = n.di_uid; /* user ID of owner */
stbuf->st_gid = n.di_gid; /* group ID of owner */
stbuf->st_size = n.di_size; /* total size, in bytes */
stbuf->st_atime = n.di_atime; /* time of last access */
stbuf->st_mtime = n.di_mtime; /* time of last modification */
stbuf->st_ctime = n.di_ctime; /* time of last status change */
return res;
}
/** Read directory
*
* This supersedes the old getdir() interface. New applications
* should use this.
*
* The filesystem may choose between two modes of operation:
*
* 1) The readdir implementation ignores the offset parameter, and
* passes zero to the filler function's offset. The filler
* function will not return '1' (unless an error happens), so the
* whole directory is read in a single readdir operation. This
* works just like the old getdir() method.
*
* 2) The readdir implementation keeps track of the offsets of the
* directory entries. It uses the offset parameter and always
* passes non-zero offset to the filler function. When the buffer
* is full (or an error happens) the filler function will return
* '1'.
*
* Introduced in version 2.3
*/
static int my_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi)
{
long index = fi->fh;//GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -ENOENT;
if(n.di_mode & S_IFDIR)
{
struct dirent items[n.di_size/sizeof(struct dirent)];
ReadFile(&n, items, 0, n.di_size);
long i;
for(i = 0; i < n.di_size/sizeof(struct dirent); i++)
{
// struct stat stbuf;
// struct dinode item = ReadInode(items[i].d_ino);
// if(item.di_size < 0)
// return -ENOENT;
// stbuf.st_ino = index; /* inode number */
// stbuf.st_mode = item.di_mode; /* protection */
// stbuf.st_nlink = item.di_nlink; /* number of hard links */
// stbuf.st_uid = item.di_uid; /* user ID of owner */
// stbuf.st_gid = item.di_gid; /* group ID of owner */
// stbuf.st_size = item.di_size; /* total size, in bytes */
// stbuf.st_atime = item.di_atime; /* time of last access */
// stbuf.st_mtime = item.di_mtime; /* time of last modification */
// stbuf.st_ctime = item.di_ctime; /* time of last status change */
filler(buf, items[i].d_name, /*&stbuf*/NULL, 0); //TODO: stat вместо NULL
}
}
else
return -ENOENT;
n.di_atime = time(NULL);
if(WriteInode(index, n) < 0)
return -EIO;
return 0;
}
/** Create a file node
*
* There is no create() operation, mknod() will be called for
* creation of all non-directory, non-symlink nodes.
*/
int my_mknod(const char *path, mode_t mode, dev_t dev)
{
if (S_ISREG(mode))
return CreateFile(path, mode | S_IFREG);
return -EINVAL;
}
/** Create a directory */
int my_mkdir(const char *path, mode_t mode)
{
//WriteToLog("mkdir: ");
//WriteToLog(path);
return(CreateDirectory(path, mode | S_IFDIR));
}
/* указатель на эту функцию будет передан модулю ядра FUSE в качестве
поля open структуры типа fuse_operations - эта функция определяет
имеет ли право пользователь открыть файл /hello нашей файловой системы -
путём анализа данных структуры типа fuse_file_info (читайте о ней ниже)*/
static int my_open(const char *path, struct fuse_file_info *fi)
{
fi->fh = GetInodeIndexByPath(path);
if((fi->fh) < 0)
return -ENOENT;
return 0;
}
/** Open directory
*
* This method should check if the open operation is permitted for
* this directory
*
* Introduced in version 2.3
*/
int my_opendir(const char *path, struct fuse_file_info *fi)
{
long index = GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -ENOENT;
fi->fh = index;
/*char message[50];
sprintf(message, "opendir flags: %o", fi->flags);
WriteToLog(message);*/
return 0;
}
/** Read data from an open file
*
* Read should return exactly the number of bytes requested except
* on EOF or error, otherwise the rest of the data will be
* substituted with zeroes. An exception to this is when the
* 'direct_io' mount option is specified, in which case the return
* value of the read system call will reflect the return value of
* this operation.
*
* Changed in version 2.2
*/
int my_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
long index = fi->fh;//GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
/*char message[500];
sprintf(message, "read: index = %ld, path = %s, size = %ld, offset = %ld, real size = %ld", index, path, size, (long)offset, n.di_size);
WriteToLog(message);*/
if(n.di_size < 0)
return -ENOENT;
if(ReadFile(&n, buf, (long)offset, size) < 0)
return -EIO;
n.di_atime = time(NULL);
if(WriteInode(index, n) < 0)
return -EIO;
//WriteToLog("SUCCESS");
return size;
}
/** Write data to an open file
*
* Write should return exactly the number of bytes requested
* except on error. An exception to this is when the 'direct_io'
* mount option is specified (see read operation).
*
* Changed in version 2.2
*/
int my_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
long index = fi->fh;//GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -ENOENT;
/*char message[500];
sprintf(message, "write: index = %ld, path = %s, size = %ld, offset = %ld, real size = %ld, fi->fh = %ld", index, path, size, (long)offset, n.di_size, fi->fh);
WriteToLog(message);*/
if(WriteFile(&n, (void *)buf, (long)offset, size) < 0)
{
return -EIO;
}
if(WriteInode(index, n) < 0)
return -EIO;
//WriteToLog("SUCCESS");
return size;
}
/** Remove a directory */
int my_rmdir(const char *path)
{
return RemoveByPath(path);
}
/** Remove a file */
int my_unlink(const char *path)
{
return RemoveByPath(path);
}
/** Get file system statistics
*
* The 'f_frsize', 'f_favail', 'f_fsid' and 'f_flag' fields are ignored
*
* Replaced 'struct statfs' parameter with 'struct statvfs' in
* version 2.5
*/
int my_statfs(const char *path, struct statvfs *statv)
{
int retstat = 0;
statv->f_bsize = ReadBlockSize();
statv->f_bsize = ReadBlockSize();
statv->f_blocks = ReadMaxBlocksCount();
statv->f_bfree = ReadFreeBlocksCount();
statv->f_bavail = statv->f_bfree;
statv->f_files = ReadMaxInodesCount();
statv->f_ffree = ReadFreeInodesCount();
statv->f_favail = statv->f_ffree;
return retstat;
}
/** Change the access and/or modification times of a file */
int my_utime(const char *path, struct utimbuf *ubuf)
{
long index = GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -ENOENT;
n.di_atime = ubuf->actime;
n.di_mtime = ubuf->modtime;
if(WriteInode(index, n) < 0)
return -EIO;
return 0;
}
/** Rename a file */
// both path and newpath are fs-relative
int my_rename(const char *path, const char *newpath)
{
return Rename(path, newpath);
}
/** Change the size of a file */
int my_truncate(const char *path, off_t newsize)
{
long index = GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
/*char message[500];
sprintf(message, "trunc: index = %ld, path = %s, offset = %ld, real size = %ld, fi->fh = %ld", index, path, (long)newsize, n.di_size);
WriteToLog(message);*/
if(n.di_size < 0)
return -ENOENT;
if(TruncFile(&n, (long)newsize) < 0)
{
return -EIO;
}
/*if((long)newsize == 0)
return FreeInodeIndex(index);*/
return(WriteInode(index, n));
}
static struct fuse_operations my_operations;
int main(int argc, char *argv[])
{
//Create();
if(Load(FILE_PATH) < 0)
{
printf("Cann't load file system.\n");
return -1;
}
my_operations.getattr = my_getattr;
my_operations.readdir = my_readdir;
my_operations.open = my_open;
my_operations.opendir = my_opendir;
my_operations.read = my_read;
my_operations.mkdir = my_mkdir;
my_operations.rmdir = my_rmdir;
my_operations.statfs = my_statfs;
my_operations.utime = my_utime;
my_operations.rename = my_rename;
my_operations.mknod = my_mknod;
my_operations.unlink = my_unlink;
my_operations.truncate = my_truncate;
my_operations.read = my_read;
my_operations.write = my_write;
return fuse_main(argc, argv, &my_operations, 0);
}
<file_sep>/showstat.c
#include "fsfileops.h"
#include <string.h>
void PrintFileSystemInfo()
{
printf("========================\n");
printf("File system info:\n");
printf("free_inodes_count = %ld\n", free_inodes_count);
printf("max_inodes_count = %ld\n", max_inodes_count);
printf("free_blocks_count = %ld\n", free_blocks_count);
printf("max_blocks_count = %ld\n", max_blocks_count);
printf("block_size = %ld\n", block_size);
printf("========================\n");
}
void PrintDir(const char *path)
{
long i;
long index = GetInodeIndexByPath(path);
printf("index = %ld\n", index);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return;
//TruncFile(&n, 268*0);
int count = n.di_size / sizeof(struct dirent);
struct dirent items[count];
printf("---------------------------------------------------\n");
printf("[%s]: size = %ld, index = %ld, links = %d\n", path, n.di_size, index, n.di_nlink);
ReadFile(&n, (void *)items, 0*sizeof(struct dirent), (count)*sizeof(struct dirent));
for(i = 0; i<count; i++)
{
struct dinode item = ReadInode((items)[i].d_ino);
printf(" %s: inode = %ld, offs = %ld, mode = %o, size = %ld\n", (items)[i].d_name, (items)[i].d_ino, (items)[i].d_off, item.di_mode, item.di_size);
if((strcmp(items[i].d_name, "..") != 0) && (strcmp(items[i].d_name, ".") != 0) && (item.di_mode & S_IFDIR))
{
char newpath[strlen(path)+strlen(items[i].d_name)+2];
strcpy(newpath, path);
if(strcmp(path, "/") != 0) strcat(newpath, "/");
strcat(newpath, items[i].d_name);
PrintDir(newpath);
}
}
printf("---------------------------------------------------\n");
}
int main(int argc, char *argv[])
{
fsfilename = FILE_PATH;
Load(fsfilename);
/*int i;
for(i = 0; i < 100; i++)
printf("index = %ld\n", GetInodeIndexByPath("/Безымянная папка/FUSE.htm"));*/
PrintDir("/");
PrintFileSystemInfo();
}
<file_sep>/createfsfile.c
#include "fsfileops.h"
#include <string.h>
long Create()
{
long i;
FILE *file;
if((file=fopen(fsfilename,"wb"))==0)
{
puts ("Can't open output file.");
return -1;
}
long max_inodes_count = MAX_INODES_COUNT;
long free_inodes_count = FREE_INODES_COUNT;
long max_blocks_count = MAX_BLOCKS_COUNT;
long free_blocks_count = FREE_BLOCKS_COUNT;
long block_size = BLOCK_SIZE;
fwrite(&free_inodes_count, sizeof(free_inodes_count), 1, file);
fwrite(&max_inodes_count, sizeof(max_inodes_count), 1, file);
fwrite(&free_blocks_count, sizeof(free_blocks_count), 1, file);
fwrite(&max_blocks_count, sizeof(max_blocks_count), 1, file);
fwrite(&block_size, sizeof(block_size), 1, file);
//fseek(output, 5*sizeof(long) + max_inodes_count * sizeof(struct dinode), SEEK_SET);
for (i=0; i<max_inodes_count; i++)
{
struct dinode n;
n.di_gen = i;
fwrite(&n, sizeof(n), 1, file);
}
for (i=max_inodes_count-1; i>=0; i--)
{
long n = i;
fwrite(&n, sizeof(n), 1, file);
}
for (i=max_blocks_count-1; i>=0; i--)
{
long n = i;
fwrite(&n, sizeof(n), 1, file);
}
/*for (i=0; i<max_blocks_count; i++)
{
long j;
for (j=0; j<block_size; j++)
{
char n = j % 128;
if(j==0)
n = i % 128;
fwrite(&n, sizeof(n), 1, file);
}
}*/
fclose(file);
return 0;
}
void PrintFileSystemInfo()
{
printf("========================\n");
printf("File system info:\n");
printf("free_inodes_count = %ld\n", free_inodes_count);
printf("max_inodes_count = %ld\n", max_inodes_count);
printf("free_blocks_count = %ld\n", free_blocks_count);
printf("max_blocks_count = %ld\n", max_blocks_count);
printf("block_size = %ld\n", block_size);
printf("========================\n");
}
long CreateRoot()
{
struct dinode n;
long index = GetNewInodeIndex();
if(index < 0)
{
/*char message[50];
sprintf(message, "Failed to create root");
WriteToLog(message);*/
return -1;
}
n.di_mode = S_IFDIR | 0777;
n.di_nlink = 2;
n.di_uid = 0; /* owner's user id */
n.di_gid = 0; /* owner's group id */
n.di_size = 0; /* number of bytes in file */
/*n.di_addr*/; /* disk block addresses */
n.di_gen = 0; /* file generation number */
n.di_atime = time(NULL); /* time last accessed */
n.di_mtime = time(NULL); /* time last modified */
n.di_ctime = time(NULL); /* time created */
struct dirent items[2];
long i;
for(i = 0; i<sizeof(n.di_addr)/sizeof(long); i++)
{
n.di_addr[i] = -1;
}
strcpy(items[0].d_name,".."); //parent
items[0].d_ino=index;
strcpy(items[1].d_name,"."); //this
items[1].d_ino=index;
for(i = 0; i<2; i++)
{
items[i].d_off = n.di_size + i * sizeof(struct dirent); /* offset to this dirent */
items[i].d_reclen = sizeof(struct dirent); /* length of this record */
items[i].d_type = -i; /* type of file; not supported by all file system types */
}
if(WriteFile(&n, items, 0, sizeof(items)) < 0)
{
/*char message[50];
sprintf(message, "Failed to create root");
WriteToLog(message);*/
return -1;
}
if(WriteInode(index, n) < 0)
{
/*char message[50];
sprintf(message, "Failed to create root");
WriteToLog(message);*/
return -1;
}
printf("Root was created\n");
}
void PrintDir(const char *path)
{
long i;
long index = GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return;
int count = n.di_size / sizeof(struct dirent);
struct dirent items[count];
printf("---------------------------------------------------\n");
printf("[%s: size = %ld, index = %ld, links = %d]\n", path, n.di_size, index, n.di_nlink);
ReadFile(&n, (void *)items, 0*sizeof(struct dirent), (count)*sizeof(struct dirent));
for(i = 0; i<count; i++)
{
struct dinode item = ReadInode((items)[i].d_ino);
printf(" %s: inode = %ld, offs = %ld, mode = %o, size = %ld\n", (items)[i].d_name, (items)[i].d_ino, (items)[i].d_off, item.di_mode, item.di_size);
}
printf("---------------------------------------------------\n");
}
int main(int argc, char *argv[])
{
fsfilename = FILE_PATH;
Create();
Load(fsfilename);
CreateRoot();
/*CreateDirectory("/test", S_IFDIR | 0777);
CreateDirectory("/test/test1", S_IFDIR | 0777);
CreateFile("/test/testf", S_IFREG | 0777);
//CreateFile("/test/test1/testf", S_IFREG | 0777);
CreateDirectory("/test/test1/test2", S_IFDIR | 0777);
//CreateFile("/test/test1/test2/testf", S_IFREG | 0777);
/*CreateDirectory("/test3", S_IFDIR | 0777);
/*CreateDirectory("/test4", S_IFDIR | 0777);
CreateDirectory("/test5", S_IFDIR | 0777);*/
/*struct dinode n = ReadInode(0);
struct dirent items[n.di_size/sizeof(dirent)];
ReadFile(n, &items, sizeof(struct dirent), n.di_size - sizeof(dirent));*/
/*long k;
for(k = 6; k < 10; k++)
{
char path[50];
sprintf(path, "/test%ld", k);
CreateDirectory(path, S_IFDIR | 0777);
}*/
Load(fsfilename);
PrintDir("/");
PrintFileSystemInfo();
}
<file_sep>/example.c
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
static const char *hello_str = "Hello World!\n";
static const char *hello_path = "/hello";
/* Далее мы определим действия функций,
которые требуются для FUSE при описании файловой системы*/
/*указатель на эту функцию будет передан модулю ядра FUSE в качестве
поля getattr структуры типа fuse_operations - эта функция определяет
метаинформацию о файле, путь к которому указан в переменной *path
метаиноформация возвращается в виде специальной структуры
stat (читайте о ней ниже)
*/
static int my_getattr(const char *path, struct stat *stbuf)
{
int res = 0;
memset(stbuf, 0, sizeof(struct stat));
if(strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
}
else if(strcmp(path, hello_path) == 0) {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = strlen(hello_str);
}
else
res = -ENOENT;
return res;
}
/* указатель на эту функцию будет передан модулю ядра FUSE в качестве
поля readdir структуры типа fuse_operations - эта функция определяет
порядок чтения данных из директория*/
static int my_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
(void) offset;
(void) fi;
if(strcmp(path, "/") != 0)
return -ENOENT;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
filler(buf, hello_path + 1, NULL, 0);
return 0;
}
/* указатель на эту функцию будет передан модулю ядра FUSE в качестве
поля open структуры типа fuse_operations - эта функция определяет
имеет ли право пользователь открыть файл /hello нашей файловой системы -
путём анализа данных структуры типа fuse_file_info (читайте о ней ниже)*/
static int my_open(const char *path, struct fuse_file_info *fi)
{
if(strcmp(path, hello_path) != 0)
return -ENOENT;
if((fi->flags & 3) != O_RDONLY)
return -EACCES;
return 0;
}
/*определяет, как именно будет считываться информация из файла для передачи пользователю*/
static int my_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
size_t len;
(void) fi;
if(strcmp(path, hello_path) != 0)
return -ENOENT;
len = strlen(hello_str);
if (offset < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, hello_str + offset, size);
} else
size = 0;
return size;
}
static struct fuse_operations my_operations; /* в этой структуре будут храниться ссылки на функции, которые реализуют операции, определённые в рамках нашей файловой системы */
int main(int argc, char *argv[])
{
// начало заполнения полей структуры
my_operations.getattr = my_getattr;
my_operations.readdir = my_readdir;
my_operations.open = my_open;
my_operations.read = my_read;
// окончание заполнения полей структуры
return fuse_main(argc, argv, &my_operations, 0); // передаём структуру с инф. об операциях модулю FUSE
}
<file_sep>/fsfileops.h
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include "inode.h"
#define MAX_INODES_COUNT 1000
#define FREE_INODES_COUNT 1000
#define MAX_BLOCKS_COUNT 1000000
#define FREE_BLOCKS_COUNT 1000000
#define BLOCK_SIZE 4096
/*#define LOG_PATH "/home/totzhe/ОС/FUSE/log"
#define FILE_PATH "/home/totzhe/ОС/FUSE/file"*/
#define LOG_PATH "/media/Study/Z/3 курс/Операционные системы/FUSE/log"
#define FILE_PATH "/media/Study/Z/3 курс/Операционные системы/FUSE/file"
char *fsfilename;
long max_inodes_count;
long free_inodes_count;
long max_blocks_count;
long free_blocks_count;
long block_size;
long param_count = 5;
//FILE *file;
void WriteToLog(const char *str)
{
FILE *output;
if((output=fopen(LOG_PATH, "a+"))==0)
{
puts ("Can't open output file.");
exit(-1);
}
fprintf(output, "%s\n", str);
fclose(output);
}
long ReadFreeInodesCount()
{
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
fseek(file, 0, SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Read free inodes count: %ld", result);
//WriteToLog(buf);*/
return result;
}
long WriteFreeInodesCount(long value)
{
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
fseek(file, 0, SEEK_SET);
fwrite(&value, sizeof(value), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Wrote free inodes count: %ld", value);
//WriteToLog(buf);*/
return 0;
}
long ReadMaxInodesCount()
{
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
fseek(file, sizeof(long), SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Read max inodes count: %ld", result);
//WriteToLog(buf);*/
return result;
}
long WriteMaxInodesCount(long value)
{
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
fseek(file, sizeof(long), SEEK_SET);
fwrite(&value, sizeof(value), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Wrote max inodes count: %ld", value);
//WriteToLog(buf);*/
return 0;
}
long ReadFreeBlocksCount()
{
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
fseek(file, 2*sizeof(long), SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Read free blocks count: %ld", result);
//WriteToLog(buf);*/
return result;
}
long WriteFreeBlocksCount(long value)
{
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
fseek(file, 2*sizeof(long), SEEK_SET);
fwrite(&value, sizeof(value), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Wrote free blocks count: %ld", value);
//WriteToLog(buf);*/
return 0;
}
long ReadMaxBlocksCount()
{
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
fseek(file, 3*sizeof(long), SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Read max blocks count: %ld", result);
//WriteToLog(buf);*/
return result;
}
long WriteMaxBlocksCount(long value)
{
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
fseek(file, 3*sizeof(long), SEEK_SET);
fwrite(&value, sizeof(value), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Wrote max blocks count: %ld", value);
//WriteToLog(buf);*/
return 0;
}
long ReadBlockSize()
{
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
fseek(file, 4*sizeof(long), SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Read block size: %ld", result);
//WriteToLog(buf);*/
return result;
}
long WriteBlockSize(long value)
{
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
fseek(file, 4*sizeof(long), SEEK_SET);
fwrite(&value, sizeof(value), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Wrote block size: %ld", value);
//WriteToLog(buf);*/
return 0;
}
long GetNewInodeIndex()
{
long count = ReadFreeInodesCount();
if(count == 0)
return -1;
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
long offset = param_count * sizeof(long) + max_inodes_count * sizeof(struct dinode) + (count - 1) * sizeof(long);
fseek(file, offset, SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
WriteFreeInodesCount(--count);
/*char buf[50];
sprintf(buf, "Got new inode index: %ld", result);
printf("Got new inode index: %ld\n", result);
//WriteToLog(buf);*/
return result;
}
long FreeInodeIndex(long index)
{
if(index < 0 || index >= max_inodes_count)
return -1;
long count = ReadFreeInodesCount();
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long offset = param_count * sizeof(long) + max_inodes_count * sizeof(struct dinode) + count * sizeof(long);
fseek(file, offset, SEEK_SET);
fwrite(&index, sizeof(index), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Inode was freed: %ld", index);
printf("Inode was freed: %ld\n", index);
//WriteToLog(buf);*/
WriteFreeInodesCount(++count);
return 0;
}
long GetNewBlockIndex()
{
long count = ReadFreeBlocksCount();
if(count == 0)
return -1;
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long result;
long offset = param_count * sizeof(long) + max_inodes_count * sizeof(struct dinode) + max_inodes_count * sizeof(long) + (count - 1) * sizeof(long);
fseek(file, offset, SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
WriteFreeBlocksCount(--count);
/*char buf[50];
sprintf(buf, "Got new block index: %ld", result);
printf("Got new block index: %ld\n", result);
//WriteToLog(buf);*/
return result;
}
long FreeBlockIndex(long index)
{
if(index < 0 || index >= max_blocks_count)
return -1;
long count = ReadFreeBlocksCount();
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long offset = param_count * sizeof(long) + max_inodes_count * sizeof(struct dinode) + max_inodes_count * sizeof(long) + count * sizeof(long);
fseek(file, offset, SEEK_SET);
fwrite(&index, sizeof(index), 1, file);
fclose(file);//fflush(file);
WriteFreeBlocksCount(++count);
/*char buf[50];
sprintf(buf, "Block was freed: %ld", index);
printf("Block was freed: %ld\n", index);
//WriteToLog(buf);*/
return 0;
}
struct dinode ReadInode(long index)
{
struct dinode result;
result.di_size = -1;
result.di_gen = -1;
if(index < 0 || index >= max_inodes_count)
return result;
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return result;
}
long offset = param_count * sizeof(long) + index * sizeof(result);
fseek(file, offset, SEEK_SET);
fread(&result, sizeof(result), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Read inode: %ld", index);
//WriteToLog(buf);*/
return result;
}
long WriteInode(long index, struct dinode value)
{
if(index < 0 || index >= max_inodes_count)
return -1;
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long offset = param_count * sizeof(long) + index * sizeof(value);
fseek(file, offset, SEEK_SET);
fwrite(&value, sizeof(value), 1, file);
fclose(file);//fflush(file);
/*char buf[50];
sprintf(buf, "Wrote inode: %ld", index);
//WriteToLog(buf);*/
return 0;
}
long ReadBlock(long index, void *buf, long offset, long size)
{
if(index < 0 || index >= max_blocks_count || offset + size > block_size)
return -1;
FILE *file;
if((file=fopen(fsfilename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long offs = (param_count + max_blocks_count + max_inodes_count) * sizeof(long) + max_inodes_count * sizeof(struct dinode) + index * block_size + offset;
fseek(file, offs, SEEK_SET);
fread(buf, size, 1, file);
fclose(file);//fflush(file);
/*char buff[50];
sprintf(buff, "Read %ld bytes from block %ld; offset = %ld", size, index, offset);
//WriteToLog(buff);*/
return 0;
}
long WriteBlock(long index, void *buf, long offset, long size)
{
////!!!printf("index = %ld, max_blocks_count = %ld, offset + size = %ld < block_size = %ld\n", index, max_blocks_count, offset + size, block_size);
if(buf == NULL || index < 0 || index >= max_blocks_count || offset + size > block_size)
return -1;
FILE *file;
if((file=fopen(fsfilename,"r+b"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
long offs = (param_count + max_blocks_count + max_inodes_count) * sizeof(long) + max_inodes_count * sizeof(struct dinode) + index * block_size + offset;
fseek(file, offs, SEEK_SET);
fwrite(buf, size, 1, file);
/*char buff[50];
sprintf(buff, "Wrote %ld bytes to block %ld; offset = %ld", size, index, offset);
//WriteToLog(buff);*/
fclose(file);//fflush(file);
return 0;
}
long Load(char *filename)
{
FILE *file;
if((file=fopen(filename,"rb"))==0)
{
//!!!printf("Can't open input file.\n");
return -1;
}
fsfilename = filename;
fread(&free_inodes_count, sizeof(free_inodes_count), 1, file);
fread(&max_inodes_count, sizeof(max_inodes_count), 1, file);
fread(&free_blocks_count, sizeof(free_blocks_count), 1, file);
fread(&max_blocks_count, sizeof(max_blocks_count), 1, file);
fread(&block_size, sizeof(block_size), 1, file);
//fseek(file, 2*sizeof(long) + max_inodes_count * sizeof(struct dinode) + max_inodes_count * sizeof(long), SEEK_SET);
/*for(i = 0; i < max_inodes_count; i++)
{
struct dinode node;
fread(&node, sizeof(node), 1, input);
//!!!printf("%ld\n", node.di_gen);
}
for(i = 0; i < max_inodes_count; i++)
{
long n;
fread(&n, sizeof(n), 1, input);
//!!!printf("%ld\n", n);
}*/
fclose(file);//fflush(file);
return 0;
}
long WriteFile(struct dinode *inode, void *buf, long offset, long size)
{
//!!!printf("SIZE = %ld\n", size);
long bytes_wrote = 0;
long block_number = 0;
long pos = offset < inode->di_size ? offset : inode->di_size;
//!!!printf("POS = %ld\n", pos);
long addr_in_block = block_size/sizeof(long);
if(pos >= 0 && pos < 10 * block_size)
{
block_number = pos / block_size;
while(bytes_wrote < size && block_number < 10)
{
if(inode->di_addr[block_number] < 0)
{
inode->di_addr[block_number] = GetNewBlockIndex();
if(inode->di_addr[block_number] < 0)
{
//WriteToLog("ERROR1");
return -1;
}
}
if(pos >= offset || (pos <= offset && offset < pos + block_size))
{
long offs = pos - block_size * block_number;
long n = (size - bytes_wrote) < block_size - offs ? (size - bytes_wrote) : block_size - offs;
//!!!printf("Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, inode->di_addr[block_number], n, offs);
/*char message[500];
sprintf(message, "Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, inode->di_addr[block_number], n, offs);
WriteToLog(message);*/
if(WriteBlock(inode->di_addr[block_number], buf + bytes_wrote, offs, n) < 0)
{
//WriteToLog("ERROR2");
return -1;
}
bytes_wrote+=n;
}
pos = (block_number + 1) * block_size;
block_number++;
}
}
if(pos >= 10 * block_size && pos < 10 * block_size + addr_in_block*block_size)
{
if(inode->di_addr[10] < 0)
{
inode->di_addr[10] = GetNewBlockIndex();
if(inode->di_addr[10] < 0)
return -1;
}
long index0 = inode->di_addr[10]; //индекс блока с прямыми адресами (адресами блоков с данными)
block_number = pos / block_size;
long count0 = block_number - 10;
//!!!printf("BLOCK_NUMBER = %ld\n", block_number);
while(count0 < addr_in_block && bytes_wrote < size)
{
long index1;//индекс блока с данными
//!!!printf("!di_size = %ld > %ld\n", inode->di_size, 10 * block_size + count0 * block_size);
if(10 * block_size + count0 * block_size < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
//!!!printf("getting new block\n");
index1 = GetNewBlockIndex();
if(index1 < 0)
return -1;
if(WriteBlock(index0, &index1, count0 * sizeof(long), sizeof(long)) < 0)
return -1;
//!!!printf("index1 = %ld, count0 * sizeof(long) = %ld\n", index1, count0 * sizeof(long));
}
//!!!printf("OFFSET = %ld\n", offset);
if(pos >= offset || (pos <= offset && offset < pos + block_size))
{
long offs = pos - block_size * block_number;
long n = (size - bytes_wrote) < block_size - offs ? (size - bytes_wrote) : block_size - offs;
//!!!printf("!Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, index1, n, offs);
/*char message[500];
sprintf(message, "Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, index1, n, offs);
WriteToLog(message);*/
if(WriteBlock(index1, buf + bytes_wrote, offs, n) < 0)
return -1;
bytes_wrote+=n;
}
pos = (block_number + 1) * block_size;
count0++;
block_number++;
}
}
if(pos >= 10 * block_size + addr_in_block*block_size && pos < 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size)
{
if(inode->di_addr[11] < 0)
{
inode->di_addr[11] = GetNewBlockIndex();
if(inode->di_addr[11] < 0)
return -1;
}
long index0 = inode->di_addr[11]; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
block_number = pos / block_size;
long count0 = (block_number-10-addr_in_block)/addr_in_block;
while(count0 < addr_in_block && bytes_wrote < size)
{
long index1; //индекс блока с прямыми адресами (адресами блоков с данными)
//!!!printf("!di_size = %ld > %ld\n", inode->di_size, 10 * block_size + count0 * block_size);
if(10 * block_size + addr_in_block * block_size + count0 * block_size * addr_in_block < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
//!!!printf("getting new block\n");
index1 = GetNewBlockIndex();
if(index1 < 0)
return -1;
if(WriteBlock(index0, &index1, count0 * sizeof(long), sizeof(long)) < 0)
return -1;
}
long count1 = (block_number-10-addr_in_block) - count0 * addr_in_block;
while(count1 < addr_in_block && bytes_wrote < size)
{
long index2; //индекс блока с данными
//!!!printf("!!di_size = %ld > %ld\n", inode->di_size, 10 * block_size + count0 * block_size);
if(10 * block_size + addr_in_block * block_size + count0 * block_size * addr_in_block + count1 * block_size < inode->di_size)
{
ReadBlock(index1, &index2, count1 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
//!!!printf("!getting new block\n");
index2 = GetNewBlockIndex();
if(index2 < 0)
return -1;
if(WriteBlock(index1, &index2, count1 * sizeof(long), sizeof(long)) < 0)
return -1;
}
//!!!printf("BLOCK_NUMBER = %ld\n", block_number);
//!!!printf("OFFSET = %ld\n", offset);
//!!!printf("index0 = %ld\n", index0);
//!!!printf("index1 = %ld\n", index1);
if(pos >= offset || (pos <= offset && offset < pos + block_size))
{
long offs = pos - block_size * block_number;
long n = (size - bytes_wrote) < block_size - offs ? (size - bytes_wrote) : block_size - offs;
//!!!printf("!!Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, index2, n, offs);
/*char message[500];
sprintf(message, "Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, index2, n, offs);
WriteToLog(message);*/
if(WriteBlock(index2, buf + bytes_wrote, offs, n) < 0)
return -1;
bytes_wrote+=n;
}
pos = (block_number + 1) * block_size;
count1++;
block_number++;
}
count0++;
}
}
if(pos >= 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size && pos < 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size + addr_in_block*addr_in_block*addr_in_block*block_size)
{
if(inode->di_addr[12] < 0)
{
inode->di_addr[12] = GetNewBlockIndex();
if(inode->di_addr[12] < 0)
return -1;
}
long index0 = inode->di_addr[12]; //индекс блока с двойными непрямыми адресами (адресами блоков с одинарными непрямыми адресами)
block_number = pos / block_size;
long count0 = (block_number-10-addr_in_block-addr_in_block*addr_in_block)/addr_in_block/addr_in_block;
while(count0 < addr_in_block && bytes_wrote < size)
{
long index1; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
//!!!printf("!!!di_size = %ld > %ld\n", inode->di_size, 10 * block_size + count0 * block_size);
if(10 * block_size + addr_in_block * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
//!!!printf("getting new block\n");
index1 = GetNewBlockIndex();
if(index1 < 0)
return -1;
if(WriteBlock(index0, &index1, count0 * sizeof(long), sizeof(long)) < 0)
return -1;
}
//!!!printf("IND1 = %ld{\n", index1);
long count1 = (block_number-10-addr_in_block-addr_in_block*addr_in_block)/addr_in_block - count0 * addr_in_block;
while(count1 < addr_in_block && bytes_wrote < size)
{
long index2; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
if(10 * block_size + addr_in_block * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block + count1 * addr_in_block * block_size < inode->di_size)
{
ReadBlock(index1, &index2, count1 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
//!!!printf("!getting new block\n");
index2 = GetNewBlockIndex();
if(index2 < 0)
return -1;
if(WriteBlock(index1, &index2, count1 * sizeof(long), sizeof(long)) < 0)
return -1;
}
//!!!printf("IND2 = %ld[\n", index2);
long count2 = (block_number-10-addr_in_block-addr_in_block*addr_in_block) - count0 * addr_in_block * addr_in_block - count1 * addr_in_block;
while(count2 < addr_in_block && bytes_wrote < size)
{
long index3; //индекс блока с прямыми адресами (адресами блоков с данными)
if(10 * block_size + addr_in_block * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block + count1 * addr_in_block * block_size + count2 * block_size < inode->di_size)
{
ReadBlock(index2, &index3, count2 * sizeof(long), sizeof(long));
if(index2 < 0)
return -1;
}
else
{
//!!!printf("!getting new block\n");
index3 = GetNewBlockIndex();
if(index3 < 0)
return -1;
if(WriteBlock(index2, &index3, count2 * sizeof(long), sizeof(long)) < 0)
return -1;
}
//!!!printf("IND3 = %ld(\n", index3);
if(pos >= offset || (pos <= offset && offset < pos + block_size))
{
long offs = pos - block_size * block_number;
long n = (size - bytes_wrote) < block_size - offs ? (size - bytes_wrote) : block_size - offs;
//!!!printf("!!Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, index3, n, offs);
/*char message[500];
sprintf(message, "Writing: bytes_wrote = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_wrote, pos, index3, n, offs);
WriteToLog(message);*/
if(WriteBlock(index3, buf + bytes_wrote, offs, n) < 0)
return -1;
bytes_wrote+=n;
}
pos = (block_number + 1) * block_size;
count2++;
block_number++;
//!!!printf(")\n");
}
count1++;
//!!!printf("]\n");
}
count0++;
//!!!printf("}\n");
}
}
inode->di_size = inode->di_size > offset + size ? inode->di_size : offset + size ;
inode->di_atime = time(NULL);
inode->di_mtime = time(NULL);
return 0;
}
long ReadFile(struct dinode *inode, void *buf, long offset, long size)
{
long bytes_read = 0;
long block_number = 0;
long pos = offset;
long addr_in_block = block_size/sizeof(long);
if(pos < inode->di_size)
{
if(pos < 10 * block_size)
{
block_number = pos / block_size;
while(bytes_read < size && block_number < 10 && pos < inode->di_size)
{
if(inode->di_addr[block_number] < 0)
{
//WriteToLog("ERR1");
return -1;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_read) < block_size - offs ? (size - bytes_read) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
////!!!printf("Reading: pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, inode->di_addr[block_number], n, offs);
/*char message[500];
sprintf(message, "Reading: bytes_read = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_read, pos, inode->di_addr[block_number], n, offs);
WriteToLog(message);*/
if(ReadBlock(inode->di_addr[block_number], buf + bytes_read, offs, n) < 0)
{
//WriteToLog("ERR2");
return -1;
}
bytes_read+=n;
pos = (block_number + 1) * block_size;
block_number++;
}
}
if(pos >= 10 * block_size && pos < 10 * block_size + addr_in_block*block_size && pos < inode->di_size)
{
if(inode->di_addr[10] < 0)
{
return -1;
}
long index0 = inode->di_addr[10]; //индекс блока с прямыми адресами (адресами блоков с данными)
block_number = pos / block_size;
long count0 = block_number - 10;
while(count0 < addr_in_block && bytes_read < size && pos < inode->di_size)
{
long index1;//индекс блока с данными
if(10 * block_size + count0 * block_size < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_read) < block_size - offs ? (size - bytes_read) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
////!!!printf("Reading: !pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, index1, n, offs);
/*char message[500];
sprintf(message, "Reading: bytes_read = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_read, pos, index1, n, offs);
WriteToLog(message);*/
if(ReadBlock(index1, buf + bytes_read, offs, n) < 0)
return -1;
bytes_read+=n;
pos = (block_number + 1) * block_size;
block_number++;
count0++;
}
}
if(pos >= 10 * block_size + addr_in_block*block_size && pos < 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size && pos < inode->di_size)
{
if(inode->di_addr[11] < 0)
{
return -1;
}
long index0 = inode->di_addr[11]; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
block_number = pos / block_size;
long count0 = (block_number-10-addr_in_block)/addr_in_block;
/*//!!!printf("POS = %ld < %ld\n", pos, 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size + addr_in_block*addr_in_block*addr_in_block*block_size);
//!!!printf("!Reading: block_number = %ld, count0 = %ld\n", block_number, count0);*/
while(count0 < addr_in_block && bytes_read < size && pos < inode->di_size)
{
long index1; //индекс блока с прямыми адресами (адресами блоков с данными)
if(10 * block_size + addr_in_block * block_size + count0 * block_size * addr_in_block < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
break;
}
long count1 = (block_number-10-addr_in_block) - count0 * addr_in_block;
while(count1 < addr_in_block && bytes_read < size && pos < inode->di_size)
{
long index2;//индекс блока с данными
if(10 * block_size + addr_in_block * block_size + count0 * block_size * addr_in_block + count1 * block_size < inode->di_size)
{
ReadBlock(index1, &index2, count1 * sizeof(long), sizeof(long));
if(index2 < 0)
return -1;
}
else
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_read) < block_size - offs ? (size - bytes_read) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
////!!!printf("Reading: !!pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, index2, n, offs);
/*char message[500];
sprintf(message, "Reading: bytes_read = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_read, pos, index2, n, offs);
WriteToLog(message);*/
if(ReadBlock(index2, buf + bytes_read, offs, n) < 0)
return -1;
bytes_read+=n;
pos = (block_number + 1) * block_size;
block_number++;
count1++;
}
count0++;
}
}
if(pos >= 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size && pos < 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size + addr_in_block*addr_in_block*addr_in_block*block_size && pos < inode->di_size)
{
if(inode->di_addr[12] < 0)
{
return -1;
}
long index0 = inode->di_addr[12]; //индекс блока с двойными непрямыми адресами (адресами блоков с одинарными непрямыми адресами)
block_number = pos / block_size;
long count0 = (block_number-10-addr_in_block-addr_in_block*addr_in_block)/addr_in_block/addr_in_block;
while(count0 < addr_in_block && bytes_read < size && pos < inode->di_size)
{
long index1; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
if(10 * block_size + addr_in_block * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
break;
}
long count1 = (block_number-10-addr_in_block-addr_in_block*addr_in_block)/addr_in_block - count0 * addr_in_block;
while(count1 < addr_in_block && bytes_read < size && pos < inode->di_size)
{
long index2; //индекс блока с прямыми адресами (адресами блоков с данными)
if(10 * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block + count1 * addr_in_block * block_size < inode->di_size)
{
ReadBlock(index1, &index2, count1 * sizeof(long), sizeof(long));
if(index2 < 0)
return -1;
}
else
{
break;
}
long count2 = (block_number-10-addr_in_block-addr_in_block*addr_in_block) - count0 * addr_in_block * addr_in_block - count1 * addr_in_block;
while(count2 < addr_in_block && bytes_read < size && pos < inode->di_size)
{
long index3; //индекс блока с данными
if(10 * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block + count1 * addr_in_block * block_size + count1 * block_size < inode->di_size)
{
ReadBlock(index2, &index3, count2 * sizeof(long), sizeof(long));
if(index3 < 0)
return -1;
}
else
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_read) < block_size - offs ? (size - bytes_read) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
////!!!printf("Reading: !!!pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, index3, n, offs);
/*char message[500];
sprintf(message, "Reading: bytes_read = %ld, pos = %ld, block = %ld, n = %ld, offs = %ld\n", bytes_read, pos, index3, n, offs);
WriteToLog(message);*/
if(ReadBlock(index3, buf + bytes_read, offs, n) < 0)
return -1;
bytes_read+=n;
pos = (block_number + 1) * block_size;
block_number++;
count2++;
}
count1++;
}
count0++;
}
}
}
if(bytes_read < size)
memset(buf+bytes_read, 0, size-bytes_read);
inode->di_atime = time(NULL);
return 0;
}
long TruncFile(struct dinode *inode, long offset)
{
long size = inode->di_size - offset;
long bytes_removed = 0;
long block_number = 0;
long pos = offset;
long addr_in_block = block_size/sizeof(long);
if(pos < 10 * block_size)
{
block_number = pos / block_size;
while(bytes_removed < size && block_number < 10)
{
if(inode->di_addr[block_number] < 0)
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_removed) < block_size - offs ? (size - bytes_removed) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
//!!!printf("Removing: pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, inode->di_addr[block_number], n, offs);
if(offs == 0)
{
if(FreeBlockIndex(inode->di_addr[block_number]) < 0)
return -1;
inode->di_addr[block_number] = -1;
}
bytes_removed+=n;
pos = (block_number + 1) * block_size;
block_number++;
}
}
if(pos >= 10 * block_size && pos < 10 * block_size + addr_in_block*block_size)
{
if(inode->di_addr[10] >= 0)
{
long index0 = inode->di_addr[10]; //индекс блока с прямыми адресами (адресами блоков с данными)
block_number = pos / block_size;
long count0 = block_number - 10;
char free_block0 = count0 == 0? 1 : 0;
while(count0 < addr_in_block && bytes_removed < size)
{
long index1;//индекс блока с данными
if(10 * block_size + count0 * block_size < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_removed) < block_size - offs ? (size - bytes_removed) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
//!!!printf("!Removing: pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, index1, n, offs);
if(offs == 0)
{
if(FreeBlockIndex(index1) < 0)
return -1;
}
else
free_block0 = 0;
bytes_removed+=n;
pos = (block_number + 1) * block_size;
block_number++;
count0++;
}
if(free_block0)
{
if(FreeBlockIndex(index0) < 0)
return -1;
inode->di_addr[10] = -1;
}
}
}
if(pos >= 10 * block_size + addr_in_block*block_size && pos < 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size)
{
if(inode->di_addr[11] < 0)
{
return -1;
}
long index0 = inode->di_addr[11]; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
block_number = pos / block_size;
long count0 = (block_number-10-addr_in_block)/addr_in_block;
char free_block0 = count0 == 0? 1 : 0;
while(count0 < addr_in_block && bytes_removed < size)
{
long index1; //индекс блока с прямыми адресами (адресами блоков с данными)
if(10 * block_size + addr_in_block * block_size + count0 * block_size * addr_in_block < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
break;
}
long count1 = (block_number-10-addr_in_block) - count0 * addr_in_block;
char free_block1 = count1 == 0? 1 : 0;
free_block0*=free_block1;
while(count1 < addr_in_block && bytes_removed < size)
{
long index2;//индекс блока с данными
if(10 * block_size + addr_in_block * block_size + count0 * block_size * addr_in_block + count1 * block_size < inode->di_size)
{
ReadBlock(index1, &index2, count1 * sizeof(long), sizeof(long));
if(index2 < 0)
return -1;
}
else
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_removed) < block_size - offs ? (size - bytes_removed) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
//!!!printf("!!Removing: pos = %ld, block = %ld, n = %ld, offs = %ld\n", pos, index2, n, offs);
if(offs == 0)
{
if(FreeBlockIndex(index2) < 0)
return -1;
}
else
{
free_block1 = 0;
free_block0 = 0;
}
bytes_removed+=n;
pos = (block_number + 1) * block_size;
block_number++;
count1++;
}
if(free_block1)
{
if(FreeBlockIndex(index1) < 0)
return -1;
}
count0++;
}
if(free_block0)
{
if(FreeBlockIndex(index0) < 0)
return -1;
inode->di_addr[11] = -1;
}
}
if(pos >= 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size && pos < 10 * block_size + addr_in_block*block_size + addr_in_block*addr_in_block*block_size + addr_in_block*addr_in_block*addr_in_block*block_size)
{
if(inode->di_addr[12] < 0)
{
return -1;
}
long index0 = inode->di_addr[12]; //индекс блока с двойными непрямыми адресами (адресами блоков с одинарными непрямыми адресами)
block_number = pos / block_size;
long count0 = (block_number-10-addr_in_block-addr_in_block*addr_in_block)/addr_in_block/addr_in_block;
char free_block0 = count0 == 0? 1 : 0;
while(count0 < addr_in_block && bytes_removed < size)
{
long index1; //индекс блока с одинарными непрямыми адресами (адресами блоков с прямыми адресами)
if(10 * block_size + addr_in_block * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block < inode->di_size)
{
ReadBlock(index0, &index1, count0 * sizeof(long), sizeof(long));
if(index1 < 0)
return -1;
}
else
{
break;
}
long count1 = (block_number-10-addr_in_block-addr_in_block*addr_in_block)/addr_in_block - count0 * addr_in_block;
char free_block1 = count1 == 0? 1 : 0;
while(count1 < addr_in_block && bytes_removed < size)
{
long index2; //индекс блока с прямыми адресами (адресами блоков с данными)
if(10 * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block + count1 * addr_in_block * block_size < inode->di_size)
{
ReadBlock(index1, &index2, count1 * sizeof(long), sizeof(long));
if(index2 < 0)
return -1;
}
else
{
break;
}
long count2 = (block_number-10-addr_in_block-addr_in_block*addr_in_block) - count0 * addr_in_block * addr_in_block - count1 * addr_in_block;
char free_block2 = count2 == 0? 1 : 0;
free_block1*=free_block2;
//printf("COUNT0 = %ld, COUNT2 = %ld, pos = %ld\n", count0, count2, pos);
while(count2 < addr_in_block && bytes_removed < size)
{
long index3; //индекс блока с данными
if(10 * block_size + addr_in_block * addr_in_block * block_size + count0 * block_size * addr_in_block * addr_in_block + count1 * addr_in_block * block_size + count1 * block_size < inode->di_size)
{
ReadBlock(index2, &index3, count2 * sizeof(long), sizeof(long));
if(index3 < 0)
return -1;
}
else
{
break;
}
long offs = pos - block_number * block_size;
long n = (size - bytes_removed) < block_size - offs ? (size - bytes_removed) : block_size - offs;
if(pos + n > inode->di_size)
n = inode->di_size - pos;
//!!!printf("!!!Removing: pos = %ld, block = %ld, n = %ld, offs = %ld, bytes_removed = %ld\n", pos, index3, n, offs, bytes_removed);
if(offs == 0)
{
if(FreeBlockIndex(index3) < 0)
return -1;
}
else
{
free_block2 = 0;
free_block1 = 0;
free_block0 = 0;
}
bytes_removed+=n;
pos = (block_number + 1) * block_size;
block_number++;
count2++;
}
count1++;
if(free_block2)
{
if(FreeBlockIndex(index2) < 0)
return -1;
}
}
free_block0*=free_block1;
count0++;
if(free_block1)
{
if(FreeBlockIndex(index1) < 0)
return -1;
}
}
if(free_block0)
{
if(FreeBlockIndex(index0) < 0)
return -1;
inode->di_addr[12] = -1;
}
}
inode->di_size = inode->di_size - bytes_removed;
inode->di_atime = time(NULL);
inode->di_mtime = time(NULL);
return 0;
}
long GetInodeIndexByPath(const char *path)
{
int pos = 0;
long index = -1;
long start = 0;
if(path[pos] == '/')
{
index = 0;
start = pos+1;
pos++;
}
else
return -ENOENT;
while(pos < strlen(path))
{
while(pos < strlen(path) && path[pos] != '/')
pos++;
char name[pos - start +1];
strncpy(name, path+start, pos - start);
name[pos - start] = '\0';
start = pos+1;
pos++;
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -ENOENT;
int count = n.di_size/sizeof(struct dirent);
struct dirent items[count];
if(ReadFile(&n, (void *)items, 0, n.di_size) < 0)
return -EIO;
int i;
index = -ENOENT;
for (i = 0; i<count; i++)
{
if(strcmp(items[i].d_name, name) == 0)
{
index = items[i].d_ino;
break;
}
}
if(index < 0)
return -ENOENT;
}
return index;
}
/*long GetInodeIndexByPath(const char *path)
{
int pos = 0;
long index = -1;
if(path[pos] == '/')
index = 0;
int l = strlen(path)+1;
char str[l];
strncpy(str, path, l);
char *pch;
pch = strtok (str,"/");
while (pch != NULL)
{
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -1;
int count = n.di_size/sizeof(struct dirent);
struct dirent items[count];
ReadFile(&n, (void *)items, 0, n.di_size);
int i;
index = -1;
for (i = 0; i<count; i++)
{
//printf ("Searching inode index by path: !%s! = !%s!\n",items[i].d_name, pch);
char message[500];
//sprintf(message, "Searching inode index by path: !%s! = !%s!\n",items[i].d_name, pch);
//WriteToLog(message);
if(strcmp(items[i].d_name, pch) == 0)
{
index = items[i].d_ino;
break;
}
}
pch = strtok (NULL, "/");
}
return index;
}*/
long RemoveHardLink(struct dinode *parent, struct dinode *child, long index)
{
struct dirent parent_items[(parent->di_size)/sizeof(struct dirent)];
ReadFile(parent, parent_items, 0, (parent->di_size));
long offs = -1;
long i;
for(i = 0; i < (parent->di_size)/sizeof(struct dirent); i++)
{
if(parent_items[i].d_ino == index)
{
offs = parent_items[i].d_off;
break;
}
}
if(offs >= 0)
{
struct dirent item;
if(ReadFile(parent, &item, (parent->di_size)-sizeof(item), sizeof(item)) < 0)
return -EIO;
item.d_off = offs;
if(WriteFile(parent, &item, offs, sizeof(item)) < 0)
return -EIO;
if(TruncFile(parent, (parent->di_size)-sizeof(item)) < 0)
return -EIO;
}
(child->di_nlink)--;
parent->di_atime = time(NULL);
parent->di_mtime = time(NULL);
return 0;
}
long AddHardLink(struct dinode *parent, struct dinode *child, long index, const char *name)
{
struct dirent parent_item;
parent_item.d_ino = index; /* inode number */
parent_item.d_off = parent->di_size; /* offset to this dirent */
parent_item.d_reclen = sizeof(parent_item); /* length of this record */
parent_item.d_type = -1; /* type of file; not supported by all file system types */
memset(parent_item.d_name, '\0', sizeof(parent_item.d_name));
strcpy(parent_item.d_name, name);
if(WriteFile(parent, (void *)&parent_item, parent->di_size, sizeof(parent_item)) < 0)
{
return -EIO;
}
(child->di_nlink)++;
parent->di_atime = time(NULL);
parent->di_mtime = time(NULL);
return 0;
}
long CreateDirectory(const char *path, mode_t mode)
{
if(GetInodeIndexByPath(path) >= 0)
{
/*//WriteToLog("ALREADY EXIST");
//WriteToLog(path);*/
return -EEXIST; //файл с таким именем уже существует
}
int l = strlen(path);
while(path[l] != '/' && l >= 0)
l--;
if(l<0)
return -ENOENT;
char parent_path[l+2];
char name[strlen(path) - l];
if(l==0)
{
strncpy(parent_path, "/", 1);
parent_path[1]='\0';
}
else
{
strncpy(parent_path, path, l);
parent_path[l]='\0';
}
strncpy(name, path+l+1, strlen(path) - l-1);
name[strlen(path) - l-1]='\0';
////WriteToLog(name);
//!!!printf("parent = %s, name = %s\n", parent_path, name);
//name = p+1;
long parent_index = GetInodeIndexByPath(parent_path);
//!!!printf("parent_index = %ld\n", parent_index);
struct dinode parent = ReadInode(parent_index);
if(parent.di_size < 0)
return -ENOENT;
if(!(parent.di_mode & S_IFDIR))
return -ENOENT;
long index = GetNewInodeIndex();
if(index < 0)
return -ENFILE;
struct dinode n;
n.di_mode = mode;
n.di_nlink = 1;
n.di_uid = 0; /* owner's user id */
n.di_gid = 0; /* owner's group id */
n.di_size = 0; /* number of bytes in file */
n.di_gen = 0; /* file generation number */
n.di_atime = time(NULL); /* time last accessed */
n.di_mtime = time(NULL); /* time last modified */
n.di_ctime = time(NULL); /* time created */
parent.di_atime = time(NULL);
parent.di_mtime = time(NULL);
struct dirent items[2];
long i;
for(i = 0; i<sizeof(n.di_addr)/sizeof(long); i++)
{
n.di_addr[i] = -1;
}
strcpy(items[0].d_name,".."); //parent
items[0].d_ino=parent_index;
strcpy(items[1].d_name,"."); //this
items[1].d_ino=index;
for(i = 0; i<2; i++)
{
items[i].d_off = n.di_size + i * sizeof(struct dirent); /* offset to this dirent */
items[i].d_reclen = sizeof(items); /* length of this record */
items[i].d_type = -i; /* type of file; not supported by all file system types */
}
AddHardLink(&parent, &n, index, name);
(parent.di_nlink)++;
if(WriteFile(&n, items, 0, sizeof(items)) < 0)
{
return -EIO;
}
if(WriteInode(index, n) < 0)
{
return -EIO;
}
if(WriteInode(parent_index, parent) < 0)
{
return -EIO;
}
return 0;
}
long GetParentIndex(const char *path)
{
int l = strlen(path);
while(path[l] != '/' && l >= 0)
l--;
if(l<0)
return -1;
char parent_path[l+2];
if(l==0)
{
strncpy(parent_path, "/", 1);
parent_path[1]='\0';
}
else
{
strncpy(parent_path, path, l);
parent_path[l]='\0';
}
printf("parent_path = %s\n", parent_path);
return GetInodeIndexByPath(parent_path);
}
long RemoveFile(struct dinode *file, long index, struct dinode *parent)
{
if(RemoveHardLink(parent, file, index) < 0)
return -EIO;
if(FreeInodeIndex(index) < 0)
return -EIO;
if(TruncFile(file, 0) < 0)
return -EIO;
return 0;
}
long RemoveDirectory(struct dinode *dir, long index, struct dinode *parent)
{
/*if(dir->di_nlink > 1)
return 0;*/
struct dirent items[(dir->di_size)/sizeof(struct dirent)];
ReadFile(dir, items, 0, (dir->di_size));
long i;
long count = (dir->di_size)/sizeof(struct dirent);
for(i = 0; i < count; i++)
{
if(!(strcmp(items[i].d_name, "..")==0) && !(strcmp(items[i].d_name, ".")==0))
{
struct dinode child = ReadInode(items[i].d_ino);
if(child.di_size < 0)
return -EIO;
if(child.di_mode & S_IFDIR)
{
if(RemoveDirectory(&child, items[i].d_ino, dir)<0)
return -EIO;
}
else
{
if(RemoveFile(&child, items[i].d_ino, dir)<0)
return -EIO;
}
}
}
if(RemoveHardLink(parent, dir, index) < 0)
return -EIO;
(parent->di_nlink)--;
if(TruncFile(dir, 0) < 0)
return -EIO;
if(FreeInodeIndex(index) < 0)
return -EIO;
return 0;
}
long RemoveByPath(const char *path)
{
long parent_index = GetParentIndex(path);
struct dinode parent = ReadInode(parent_index);
if(parent.di_size < 0)
return -1;
long index = GetInodeIndexByPath(path);
if(index < 0)
return -1;
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -1;
if(n.di_mode & S_IFDIR)
{
if(RemoveDirectory(&n, index, &parent) < 0)
return -EIO;
}
else
{
if(RemoveFile(&n, index, &parent)<0)
return -EIO;
}
if(WriteInode(parent_index, parent) < 0)
return -1;
return 0;
}
long Rename(const char *path, const char *newpath)
{
int l = strlen(newpath);
while(newpath[l] != '/' && l >= 0)
l--;
if(l<0)
return -ENOENT;
char name[strlen(newpath) - l];
strncpy(name, newpath+l+1, strlen(newpath) - l-1);
name[strlen(newpath) - l-1]='\0';
/*if(l > strlen(path) && strncmp(path, newpath, strlen(path)) == 0)
if(newpath[strlen(path)] == '/')
return -EPERM;*/
long index = GetInodeIndexByPath(path);
struct dinode n = ReadInode(index);
if(n.di_size < 0)
return -ENOENT;
long parent_index = GetParentIndex(path);
struct dinode parent = ReadInode(parent_index);
if(parent.di_size < 0)
return -ENOENT;
long new_parent_index = GetParentIndex(newpath);
struct dinode *new_parent;
if(parent_index == new_parent_index)
{
new_parent = &parent;
}
else
{
struct dinode tmp = ReadInode(new_parent_index);
new_parent = &tmp;
}
if(new_parent->di_size < 0)
return -ENOENT;
if(RemoveHardLink(&parent, &n, index) < 0)
return -EIO;
if(AddHardLink(new_parent, &n, index, name) < 0)
return -EIO;
if(n.di_mode & S_IFDIR)
{
(parent.di_nlink)--;
(new_parent->di_nlink)++;
struct dirent item;
item.d_ino = new_parent_index;
item.d_off = 0;
item.d_reclen = sizeof(item);
strcpy(item.d_name, "..");
if(WriteFile(&n, (void *)&item, 0, sizeof(item)) < 0)
{
return -EIO;
}
}
if(WriteInode(new_parent_index, *new_parent) < 0)
{
return -EIO;
}
if(WriteInode(parent_index, parent) < 0)
{
return -EIO;
}
n.di_atime = time(NULL);
n.di_mtime = time(NULL);
if(WriteInode(index, n) < 0)
{
return -EIO;
}
return 0;
}
long CreateFile(const char *path, mode_t mode)
{
if(GetInodeIndexByPath(path) >= 0)
{
/*//WriteToLog("ALREADY EXIST");
//WriteToLog(path);*/
return -EEXIST; //файл с таким именем уже существует
}
int l = strlen(path);
while(path[l] != '/' && l >= 0)
l--;
if(l<0)
return -ENOENT;
char parent_path[l+2];
char name[strlen(path) - l];
if(l==0)
{
strncpy(parent_path, "/", 1);
parent_path[1]='\0';
}
else
{
strncpy(parent_path, path, l);
parent_path[l]='\0';
}
strncpy(name, path+l+1, strlen(path) - l-1);
name[strlen(path) - l-1]='\0';
long parent_index = GetInodeIndexByPath(parent_path);
struct dinode parent = ReadInode(parent_index);
if(!(parent.di_mode & S_IFDIR))
return -ENOTDIR;
if(parent.di_size < 0)
return -ENOENT;
long index = GetNewInodeIndex();
if(index < 0)
return -ENFILE;
struct dinode n;
n.di_mode = mode;
n.di_nlink = 0;
n.di_uid = 0; /* owner's user id */
n.di_gid = 0; /* owner's group id */
n.di_size = 0; /* number of bytes in file */
n.di_gen = 0; /* file generation number */
n.di_atime = time(NULL); /* time last accessed */
n.di_mtime = time(NULL); /* time last modified */
n.di_ctime = time(NULL); /* time created */
int i;
for(i = 0; i<sizeof(n.di_addr)/sizeof(long); i++)
{
n.di_addr[i] = -1;
}
parent.di_atime = time(NULL);
parent.di_mtime = time(NULL);
AddHardLink(&parent, &n, index, name);
if(WriteInode(index, n) < 0)
{
return -EIO;
}
if(WriteInode(parent_index, parent) < 0)
{
return -EIO;
}
return 0;
}
<file_sep>/inode.h
/* Inode structure as it appears on an inode table. */
struct dinode
{ ushort di_mode; /* mode and type of file */
short di_nlink; /* number of links to file */
ushort di_uid; /* owner's user id */
ushort di_gid; /* owner's group id */
long di_size; /* number of bytes in file */
long di_addr[13]; /* disk block addresses */
long di_gen; /* file generation number */
time_t di_atime; /* time last accessed */
time_t di_mtime; /* time last modified */
time_t di_ctime; /* time created */
};
/*
* The 40 address bytes:
* 39 used as 13 addresses of 3 bytes each.
* 40th byte is used as a file generation number.
*/
struct dirent {
long d_ino; /* inode number */
long d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* filename */
};
<file_sep>/compile
#!/bin/bash
gcc test.c -o test -lfuse -D_FILE_OFFSET_BITS=64 -DFUSE_USE_VERSION=26
| 3240371eba4bb207566b593aa84ab757da869470 | [
"C",
"Shell"
] | 7 | C | adonskikh/FUSE | f6e89d27752c09f03820386e1b775f6b6a7eb8db | 3ad9a8caee0acc06a50ec8b8253f22e286cde0af | |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using EnglishLeagues.Models;
using EnglishLeagues.Services;
namespace EnglishLeagues.Controllers
{
public class HomeController : Controller
{
private LeagueService _leagueService;
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger, LeagueService service)
{
_logger = logger;
_leagueService = service;
}
/*public IActionResult Index()
{
return View();
}*/
public IActionResult Index()
{
ViewBag.Message = "Hello ASP.NET Core";
ViewBag.BestTeams = _leagueService.GetBestAttackTeams();
ViewBag.BestDefTeams = _leagueService.GetBestDefTeams();
ViewBag.BestStatTeams = _leagueService.GetBestStatisticTeams();
ViewBag.MostResultDay = _leagueService.GetMostResultDay();
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
<file_sep>using EnglishLeagues.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Ries
{
public class LeaguesRepository
{
public League GetLeagues(string fileName)
{
string jsonString = File.ReadAllText(fileName);
return JsonConvert.DeserializeObject<League>(jsonString);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class BestTeam
{
public string Team { get; set; }
public int Score { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class MostResultDay
{
public string DayName { get; set; }
public string LeagueName { get; set; }
public int Score { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class BestStatistic
{
public string Name { get; set; }
public int Scored { get; set; }
public int Missed { get; set; }
public int Difference()
{
return Scored - Missed;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class ScoreDifferences
{
public int ScoreDiff { get; set; }
public int Score { get; set; }
public void addScore(int _score)
{
Score += _score;
}
public void addScoreDiff(int _scoreDiff)
{
ScoreDiff += _scoreDiff;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class League
{
public string Name { get; set; }
public Match[] Matches;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class BestDefTeam
{
public string Team { get; set; }
public int Score { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace EnglishLeagues.Models
{
public class Score
{
public int[] ft;
}
}
<file_sep>using EnglishLeagues.Models;
using EnglishLeagues.Ries;
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EnglishLeagues.Services
{
public class LeagueService
{
private string en1 = Path.GetFullPath("Data/en.1.json");
private string en2 = Path.GetFullPath("Data/en.2.json");
private string en3 = Path.GetFullPath("Data/en.3.json");
private LeaguesRepository _repository;
public LeagueService(LeaguesRepository repository)
{
_repository = repository;
}
private Dictionary<string, int> GetBestAttackTeamDict(League league)
{
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach(var x in league.Matches)
{
if(x.Score!=null)
{
if (!temp.ContainsKey(x.Team1))
{
temp.Add(x.Team1, x.Score.ft[0]);
}
else
{
temp[x.Team1] += x.Score.ft[0];
}
if (!temp.ContainsKey(x.Team2))
{
temp.Add(x.Team2, x.Score.ft[1]);
}
else
{
temp[x.Team2] += x.Score.ft[1];
}
}
}
return temp;
}
private Dictionary<string, int> GetDayDict(League league)
{
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach(var x in league.Matches)
{
if (x.Score != null)
{
if (!temp.ContainsKey(x.Round))
{
temp.Add(x.Round, x.Score.ft[0] + x.Score.ft[1]);
}
else
{
temp[x.Round] += x.Score.ft[0] + x.Score.ft[1];
}
}
}
return temp;
}
private Dictionary<string, int> GetBestDefenceTeamDict(League league)
{
Dictionary<string, int> temp = new Dictionary<string, int>();
foreach (var x in league.Matches)
{
if (x.Score != null)
{
if (!temp.ContainsKey(x.Team1))
{
temp.Add(x.Team1, x.Score.ft[1]);
}
else
{
temp[x.Team1] += x.Score.ft[1];
}
if (!temp.ContainsKey(x.Team2))
{
temp.Add(x.Team2, x.Score.ft[0]);
}
else
{
temp[x.Team2] += x.Score.ft[0];
}
}
}
return temp;
}
public List<BestTeam> GetBestAttackTeams()
{
List<BestTeam> bestTeams = new List<BestTeam>();
League league1 = _repository.GetLeagues(en1);
League league2 = _repository.GetLeagues(en2);
League league3 = _repository.GetLeagues(en3);
Dictionary<string, int> league1Dict = GetBestAttackTeamDict(league1);
Dictionary<string, int> league2Dict = GetBestAttackTeamDict(league2);
Dictionary<string, int> league3Dict = GetBestAttackTeamDict(league3);
var league1MaxValue = league1Dict.FirstOrDefault(x => x.Value == league1Dict.Values.Max());
var league2MaxValue = league2Dict.FirstOrDefault(x => x.Value == league2Dict.Values.Max());
var league3MaxValue = league3Dict.FirstOrDefault(x => x.Value == league3Dict.Values.Max());
bestTeams.Add(new BestTeam { Team = league1MaxValue.Key, Score = league1MaxValue.Value });
bestTeams.Add(new BestTeam { Team = league2MaxValue.Key, Score = league2MaxValue.Value });
bestTeams.Add(new BestTeam { Team = league3MaxValue.Key, Score = league3MaxValue.Value });
return bestTeams;
}
public List<BestDefTeam> GetBestDefTeams()
{
List<BestDefTeam> bestDefTeams = new List<BestDefTeam>();
League league1 = _repository.GetLeagues(en1);
League league2 = _repository.GetLeagues(en2);
League league3 = _repository.GetLeagues(en3);
Dictionary<string, int> league1Dict = GetBestDefenceTeamDict(league1);
Dictionary<string, int> league2Dict = GetBestDefenceTeamDict(league2);
Dictionary<string, int> league3Dict = GetBestDefenceTeamDict(league3);
var league1MinValue = league1Dict.FirstOrDefault(x => x.Value == league1Dict.Values.Min());
var league2MinValue = league2Dict.FirstOrDefault(x => x.Value == league2Dict.Values.Min());
var league3MinValue = league3Dict.FirstOrDefault(x => x.Value == league3Dict.Values.Min());
bestDefTeams.Add(new BestDefTeam { Team = league1MinValue.Key, Score = league1MinValue.Value });
bestDefTeams.Add(new BestDefTeam { Team = league2MinValue.Key, Score = league2MinValue.Value });
bestDefTeams.Add(new BestDefTeam { Team = league3MinValue.Key, Score = league3MinValue.Value });
return bestDefTeams;
}
private Dictionary<string, ScoreDifferences> GetBestDifferenceDict(League league)
{
Dictionary<string, ScoreDifferences> temp = new Dictionary<string, ScoreDifferences>();
foreach (var x in league.Matches)
{
if (x.Score != null)
{
if (!temp.ContainsKey(x.Team1))
{
temp.Add(x.Team1, new ScoreDifferences()
{
Score = x.Score.ft[0],
ScoreDiff = x.Score.ft[0] - x.Score.ft[1]
});
}
else
{
temp[x.Team1].addScore(x.Score.ft[0]);
temp[x.Team1].addScoreDiff(x.Score.ft[0] - x.Score.ft[1]);
}
if (!temp.ContainsKey(x.Team2))
{
temp.Add(x.Team2, new ScoreDifferences()
{
Score = x.Score.ft[1],
ScoreDiff = x.Score.ft[1] - x.Score.ft[0]
});
}
else
{
temp[x.Team2].addScore(x.Score.ft[1]);
temp[x.Team2].addScoreDiff(x.Score.ft[1] - x.Score.ft[0]);
}
}
}
return temp;
}
public List<BestStatistic> GetBestStatisticTeams()
{
List<BestStatistic> bestStat = new List<BestStatistic>();
League league1 = _repository.GetLeagues(en1);
League league2 = _repository.GetLeagues(en2);
League league3 = _repository.GetLeagues(en3);
Dictionary<string, ScoreDifferences> league1Dict = GetBestDifferenceDict(league1);
Dictionary<string, ScoreDifferences> league2Dict = GetBestDifferenceDict(league2);
Dictionary<string, ScoreDifferences> league3Dict = GetBestDifferenceDict(league3);
var league1BestStat = league1Dict.FirstOrDefault(x => x.Value.ScoreDiff == league1Dict.Values.Max(o => o.ScoreDiff)
|| x.Value.Score == league1Dict.Values.Max(x => x.Score));
var league2BestStat = league2Dict.FirstOrDefault(x => x.Value.ScoreDiff == league2Dict.Values.Max(o => o.ScoreDiff)
|| x.Value.Score == league2Dict.Values.Max(x => x.Score));
var league3BestStat = league3Dict.FirstOrDefault(x => x.Value.ScoreDiff == league3Dict.Values.Max(o => o.ScoreDiff)
|| x.Value.Score == league3Dict.Values.Max(x => x.Score));
bestStat.Add(new BestStatistic {
Name = league1BestStat.Key,
Scored = league1BestStat.Value.Score,
Missed = league1BestStat.Value.Score - league1BestStat.Value.ScoreDiff
});
bestStat.Add(new BestStatistic
{
Name = league2BestStat.Key,
Scored = league2BestStat.Value.Score,
Missed = league2BestStat.Value.Score - league2BestStat.Value.ScoreDiff
});
bestStat.Add(new BestStatistic
{
Name = league3BestStat.Key,
Scored = league3BestStat.Value.Score,
Missed = league3BestStat.Value.Score - league3BestStat.Value.ScoreDiff
});
return bestStat;
}
public MostResultDay GetMostResultDay()
{
List<MostResultDay> mostResultDays = new List<MostResultDay>();
League league1 = _repository.GetLeagues(en1);
League league2 = _repository.GetLeagues(en2);
League league3 = _repository.GetLeagues(en3);
Dictionary<string, int> league1Dict = GetDayDict(league1);
Dictionary<string, int> league2Dict = GetDayDict(league2);
Dictionary<string, int> league3Dict = GetDayDict(league3);
var league1MostResultDay = league1Dict.FirstOrDefault(x => x.Value == league1Dict.Values.Max());
var league2MostResultDay = league2Dict.FirstOrDefault(x => x.Value == league2Dict.Values.Max());
var league3MostResultDay = league3Dict.FirstOrDefault(x => x.Value == league3Dict.Values.Max());
mostResultDays.Add(new MostResultDay
{
DayName = league1MostResultDay.Key,
LeagueName = league1.Name,
Score = league1MostResultDay.Value
});
mostResultDays.Add(new MostResultDay
{
DayName = league2MostResultDay.Key,
LeagueName = league2.Name,
Score = league2MostResultDay.Value
});
mostResultDays.Add(new MostResultDay
{
DayName = league2MostResultDay.Key,
LeagueName = league2.Name,
Score = league2MostResultDay.Value
});
var totalMostResultDay = mostResultDays.FirstOrDefault(x => x.Score == mostResultDays.Max(o => o.Score));
MostResultDay mostResultDay = new MostResultDay
{
DayName = totalMostResultDay.DayName,
Score = totalMostResultDay.Score,
LeagueName = totalMostResultDay.LeagueName
};
return mostResultDay;
}
}
}
| f6e06a9bf027b438e7aa1c838b341318d629da84 | [
"C#"
] | 10 | C# | NazarKavka/EnglishLeague | df8c7e82a5cd2e8d56be812079a5d8a4645416cf | f7c7ac76d6758e9fcf615a4dc55bb2f8b3e32004 | |
refs/heads/main | <repo_name>sapmanoj/manoj<file_sep>/newtone.py
def proterm(i, value, x):
pro = 1;
for j in range(i):
pro = pro * (value - x[j]);
return pro;
# Function for calculating
# divided difference table
def dividedDiffTable(x, y, n):
for i in range(1, n):
for j in range(n - i):
y[j][i] = ((y[j][i - 1] - y[j + 1][i - 1]) /
(x[j] - x[i + j]));
return y;
# Function for applying Newton's
# divided difference formula
def applyFormula(value, x, y, n):
sum = y[0][0];
for i in range(1, n):
sum = sum + (proterm(i, value, x) * y[0][i]);
return sum;
# Function for displaying divided
# difference table
def printDiffTable(y, n):
for i in range(n):
for j in range(n - i):
print(round(y[i][j], 4), "\t",
end = " ");
print("");
# Driver Code
# number of inputs given
n = 5;
y = [[0 for i in range(10)]
for j in range(10)];
x = [ 11, 12, 13, 14,15 ];
# y[][] is used for divided difference
# table where y[][0] is used for input
y[0][0] = 2435;
y[1][0] = 2475;
y[2][0] = 2490;
y[3][0] = 2487;
y[4][0] = 2506;
# calculating divided difference table
y=dividedDiffTable(x, y, n);
# displaying divided difference table
printDiffTable(y, n);
# value to be interpolated
value = 16;
# printing the value
print("\nValue at", value, "is",
round(applyFormula(value, x, y, n), 2))
# This code is contributed by mits
<file_sep>/01.py
for i in range(0,10):
for j in range(0,10-i):
print(" ",end="")
for k in range(0,2*i+1):
print("0",end="")
print("")<file_sep>/Emailsend.py
import smtplib
msz="hello this is message from ncitday19"
a=smtplib.SMTP('smtp.gmail.com',587)
a.ehlo()
a.starttls()
mail.login('<EMAIL>','itsme1234')
mail.sendmail('<EMAIL>','<EMAIL>',msz)
mail.close()
<file_sep>/06.py
import tkinter as Tkinter
import time
BALL_SPEED=5
class GameCanvas(Tkinter.Canvas):
def __init__(self, *args, **kwargs):
Tkinter.Canvas.__init__(self, *args, **kwargs)
self.create_bouncing_ball()
self.create_moving_bat()
def create_moving_bat(self):
self.bat=Tkinter.Canvas.create_rectangle(self,0,570,100,580, fill='lightslateblue')
self.bind('<Motion>', self.update_bat_moves)
return
def update_bat_moves(self, event=None):
x=event.x
x1,y1,x2,y2=self.coords(self.bat)
gap=(x2-x1)/2
center=x1+gap
move=x-center
self.move(self.bat,move,0)
return
def create_bouncing_ball(self):
self.ball=Tkinter.Canvas.create_oval(self, 0,0,20,20, fill='cornflowerblue')
self.x=BALL_SPEED
self.y=BALL_SPEED
return
def update_board(self):
width=self.winfo_width()
height=self.winfo_height()
x1,y1,x2,y2=self.coords(self.ball)
hit=len(self.find_overlapping(x1,y1,x2,y2))
if hit>=2:
self.y=-BALL_SPEED
self.move(self.ball,self.x,self.y)
elif x1<0:
self.x=BALL_SPEED
self.move(self.ball,self.x,self.y)
elif x2>width:
self.x=-BALL_SPEED
self.move(self.ball,self.x,self.y)
elif y1<0:
self.y=BALL_SPEED
self.move(self.ball,self.x,self.y)
elif y2>height:
x=width/2
y=height/2
self.create_text(x,y, text='Game Over', font=('arial 50 bold'), fill='red')
self.y=-BALL_SPEED
self.move(self.ball,self.x,self.y)
else:
self.move(self.ball,self.x,self.y)
return
def main():
root=Tkinter.Tk()
root.minsize(800,600)
root.maxsize(800,600)
board=GameCanvas(root, bg='lavender')
board.pack(expand='yes', fill='both')
# Program Loop
while True:
root.update()
root.update_idletasks()
board.update_board()
time.sleep(0.01)
# main Trigger
if __name__=='__main__':
main()<file_sep>/num2word.py
number=[" ","one","Two","Three","four","Five","Six","Seven","eight","nine"]
nty=[" "," ","Twenty","Thirty","fourty","Fifty","Sixty","Seventy","eighty","ninty"]
tens=["ten"," eleven","twelve","thirteen","fourteen","Fifteen","Sixteen","Seventeen","eighteen","ninteen"]
n=int(input("enter a number"))
if n>99999:
print("cant solve for more than 5 digits")
else:
d=[0,0,0,0,0,]
i=0
while n>0:
d[i]=n%10
i+=1
n=n//10
num=""
if d[4]!=0:
if(d[4]==1):
num+=tens[d[3]]+" thousands "
else:
num+=nty[d[4]]+" "+number[d[3]]+" thousands "
else:
if d[3]!=0:
num+=number[d[3]]+" thousands "
if d[2]!=0:
num+=number[d[2]]+" Hundred "
if d[1]!=0:
if(d[1]==1):
num+=tens[d[0]]
else:
num+=nty[d[1]]+" "+number[d[0]]
else:
if d[0]!=0:
num+=number[d[0]]
print(num)
<file_sep>/04.py
import turtle
wn=turtle.Screen()
wn.title("Pong")
wn.bgcolor("blue")
wn.setup(width=800,height=600)
wn.tracer(0)
#paddle A
paddle_a=turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("circle")
paddle_a.color("black")
paddle_a.shapesize(stretch_wid=5,stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350,0)
#paddle B
#ball
#main game loop
while True:
wn.update() | a29cba16e6c4a076f5cdb4ce44c1e41c8fa1a3f7 | [
"Python"
] | 6 | Python | sapmanoj/manoj | 4c738ec823fb7ae3f7cf97d89d74fb253b6d366a | 22bbee72606e88d162e5dccbb5290e3c459130da | |
refs/heads/main | <file_sep>import React from 'react';
import logo from '../../image/ekota academy white-01.png';
import { Link } from 'react-router-dom';
import './Navbar.css';
const Navbar = () => {
return (
<div className="menubar" style={{ fontFamily: 'Poppins' }}>
<nav class="navbar navbar-expand-lg navbar-dark bg-transparent">
<div class="container-fluid">
<Link to='/home'><a class="navbar-brand" href="#"> <img className="img-fluid" src={logo} alt="" /> </a></Link>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse " id="navbarNavDropdown">
<ul class="navbar-nav">
<li class="nav-item">
<Link to='/home'><a class="nav-link active" aria-current="page" href="#">Home</a></Link>
</li>
{/* <li class="nav-item">
<Link to='/abouts'><a class="nav-link active" href="#">About Us</a></Link>
</li> */}
<li class="nav-item dropdown ">
<a class="nav-link dropdown-toggle active" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
About Us
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<Link to='/abouts'>
<li><a class="dropdown-item" href="#">About Ekota</a></li>
</Link>
<Link to='/governance'>
<li><a class="dropdown-item" href="#">Governance</a></li>
</Link>
</ul>
</li>
{/* <li class="nav-item">
<Link to='/club'><a class="nav-link active" href="#">Our Team</a></Link>
</li> */}
<li class="nav-item dropdown ">
<a class="nav-link dropdown-toggle active" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Our Team
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdown">
<Link to='/club'>
<li><a class="dropdown-item" href="#">Team</a></li>
</Link>
<li><a class="dropdown-item" href="http://localhost:3000/club/#management">Trustees</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/club/#volunteer">Volunteer</a></li>
</ul>
</li>
{/* <li class="nav-item">
<Link to='/join'><a class="nav-link active" aria-current="page" href="#">Sports</a></Link>
</li> */}
<li class="nav-item dropdown ">
<a class="nav-link dropdown-toggle active" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Sports
</a>
<ul class="dropdown-menu " aria-labelledby="navbarDropdown">
<Link to='/join'>
<li><a class="dropdown-item" href="#">Sports</a></li>
</Link>
<li><a class="dropdown-item" href="http://localhost:3000/football">Football</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/cricket">Cricket</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/join/#martial">Martial Arts</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/join/#badminton">Badminton</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/join/#walking">Walking Cricket</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/join/#">Futsal</a></li>
</ul>
</li>
{/* <li class="nav-item">
<Link to='/community'><a class="nav-link active" href="#">Community</a></Link>
</li> */}
<li class="nav-item dropdown ">
<a class="nav-link dropdown-toggle active" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" data-hover="dropdown" aria-expanded="false">
Communities
</a>
<ul class="dropdown-menu " aria-labelledby="navbarDropdown">
<Link to='/community'>
<li><a class="dropdown-item" href="#">Community</a></li>
</Link>
<li><a class="dropdown-item" href="http://localhost:3000/community/#population">Population Health and Inequalities </a></li>
<li><a class="dropdown-item" href="http://localhost:3000/projects">Projects</a></li>
<li><a class="dropdown-item" href="http://localhost:3000/youth">Youth Support</a></li>
</ul>
</li>
<li class="nav-item">
<Link to='/news'><a class="nav-link active" href="#">News</a></Link>
</li>
{/* <li class="nav-item">
<Link to='/youth'><a class="nav-link active" href="#">Youth Support</a></Link>
</li> */}
<li class="nav-item">
<Link to='/contact'><a class="nav-link active" href="#">Contact</a></Link>
</li>
<div className="icon d-flex justify-content-center align-items-center">
<li class="nav-item ">
<a class="nav-link active" href="https://mysportshive.com/dashboard/pages/authentication/ekotaacademy/login" className="btn">Log In</a>
</li>
</div>
</ul>
</div>
</div>
</nav>
</div>
);
};
export default Navbar;<file_sep>import React from 'react';
import './Header.css';
const Header = () => {
return (
<div style={{fontFamily: 'Poppins'}} className="text-white header">
{/* <h1>The Place to Be</h1> */}
</div>
);
};
export default Header;<file_sep>import React from 'react';
const Testimonials = () => {
return (
<div>
<div className="testimonials coach text-center ">
<div className="container">
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<h1>‘’</h1>
<p>‘’Ekota has helped my child to develop new skills and I can see the week on week physical improvements and he is always excited to attend the sessions.’’</p>
<h4>Parker</h4>
</div>
<div class="carousel-item">
<h1>‘’</h1>
<p>‘’My kid absolutely love sports camp. Super positive experience for the summer.’’</p>
<h4><NAME></h4>
</div>
<div class="carousel-item">
<h1>‘’</h1>
<p>‘’Ekota has helped my child to develop new skills and I can see the week on week physical improvements and he is always excited to attend the sessions.’’</p>
<h4>Parker</h4>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</div>
>
</div>
</div>
);
};
export default Testimonials;<file_sep>import React from 'react';
import Navbar from '../../Navbar/Navbar';
import image from '../../../image/ZQgXhC84UabKkGfmeXpsDnR3q8jBok0ZJIJUkXQ86FoeJxFPc (1).jfif';
import image1 from '../../../image/1X_u4PD9kdIdelCkR0rAx4aVDWE_wMwBQrgpC_XoeQ8eJxFPc.jfif';
import image2 from '../../../image/27Yoy53ty915jjw2-4k43pqxxnoxY7dTcoHg8zM6SI0eJxFPc.jfif';
import image3 from '../../../image/WlHzIft4vXCIj0hAebsU-4VivWE-w-eTwFB8qb1gevYeJxFPc.jfif';
import image4 from '../../../image/w29AnzRvddYhL8qZM_tAO2mzE62pRWHp-AdFzPYC70seJxFPc.jfif';
import image5 from '../../../image/XiVfsE3_dyVTYXplNBI0SGqgLj4oqJouGcBKGtoOYhkeJxFPc.jfif';
import image6 from '../../../image/ZxwIyWXZeplybiE7OC2sWG4dkAj9MMRTQFw1uMIG3WAeJxFPc.jfif';
import image7 from '../../../image/w29AnzRvddYhL8qZM_tAO2mzE62pRWHp-AdFzPYC70seJxFPc.jfif';
import image8 from '../../../image/vrGKTI-jGfxrSQiS6CCOmvCOlZ_sb6gI452cZV5AwzseJxFPc.jfif';
import image9 from '../../../image/06oT2scMvgjJ0A0-IGD0QTJ5FCmzzQzwHjzpU0VU_WkeJxFPc.jfif';
import image10 from '../../../image/8aTcZC1rSosgoBywMEKoIZpvPHaIZfqMUxYg1NCJvUseJxFPc.jfif';
import image11 from '../../../image/4-Gwi2ybKO94JlYR-sO5rQW19QssOArQ0UJ8-lxdm-geJxFPc.jfif';
import image12 from '../../../image/6LCp6XpB5SjCW6S5TAuaEyxjHI2Rrb8TssarkCAAebYeJxFPc.jfif';
import image13 from '../../../image/_6eXHo5z9xPNbksmoSg59VGOOgJti88zwJlE0ko3TzoeJxFPc - Copy.jfif';
import image14 from '../../../image/bdP0BJ6gXq2mZUjvEzW_yT6pSkelIqPFbdONzKwQm0MeJxFPc.jfif';
import video from '../../../video/Comp 1.mp4';
import './GallerySecond.css'
import Footer from '../../Footer/Footer';
const GallerySecond = () => {
return (
<div >
<div className="gallery-bg">
<Navbar></Navbar>
</div>
<div className="container-fluid">
<h1 className="text-center mt-5 mb-5">Ekota Academy Pictures & Videos</h1>
<div className="row mb-2 g-1">
<div className="col-md-7">
<img src={image} alt="" className="img-fluid" />
</div>
<div className="col-md-5">
<img src={image1} alt="" className="img-fluid gallery-img1" />
</div>
</div>
<div className="row mb-2 g-1">
<div className="col-md-5">
<img src={image2} alt="" className="img-fluid gallery-img1" />
</div>
<div className="col-md-7">
<img src={image3} alt="" className="img-fluid gallery-img2 w-100 " />
</div>
</div>
<div className="row mb-2 g-1">
<div className="col-md-4">
<img src={image4} alt="" className="img-fluid" />
</div>
<div className="col-md-4">
<img src={image5} alt="" className="img-fluid" />
</div>
<div className="col-md-4">
<img src={image6} alt="" className="img-fluid" />
</div>
</div>
<div className="row g-0">
<div className="col-md-6">
<video className="gallery-video" autoPlay loop muted>
<source src={video} type="video/mp4" />
</video>
</div>
<div className="col-md-6">
<video className="gallery-video" autoPlay loop muted>
<source src={video} type="video/mp4" />
</video>
</div>
</div>
<div className="row mb-2 g-1">
<div className="col-md-4">
<img src={image7} alt="" className="img-fluid" />
</div>
<div className="col-md-4">
<img src={image8} alt="" className="img-fluid" />
</div>
<div className="col-md-4">
<img src={image9} alt="" className="img-fluid" />
</div>
</div>
<div className="row mb-2 g-1">
<div className="col-md-7">
<img src={image10} alt="" className="img-fluid" />
</div>
<div className="col-md-5">
<img src={image11} alt="" className="img-fluid gallery-img1" />
</div>
</div>
<div className="row mb-2 g-1">
<div className="col-md-4">
<img src={image12} alt="" className="img-fluid" />
</div>
<div className="col-md-4">
<img src={image13} alt="" className="img-fluid gallery-img13" />
</div>
<div className="col-md-4">
<img src={image14} alt="" className="img-fluid " />
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default GallerySecond;<file_sep>import React from 'react';
import pictures from '../../image/sx4GAJRVn1zCUV784eb8xNyeaGihP6BjmdIBCbkPWHMeJxFPc.jfif';
import Footer from '../Footer/Footer';
import Navbar from '../Navbar/Navbar';
import image from '../../image/1X_u4PD9kdIdelCkR0rAx4aVDWE_wMwBQrgpC_XoeQ8eJxFPc.jfif';
import news from '../../image/Screenshot-2021-03-26-at-18.52.38-1500x844.png';
import image2 from '../../image/Screenshot-2021-03-29-at-11.26.58-1500x844.png';
import image1 from '../../image/Grouppic-1500x803.jpg';
import image3 from '../../image/20200826_112019-1500x701.jpg';
import logo from '../../image/Sport-England-Logo-Blue-(CMYK).png';
import logo1 from '../../image/Eagles_in_the_Community_Logo_2018_1-removebg-preview.png';
import logo2 from '../../image/Vision Logo 2018 FINAL transparent.png';
import logo3 from '../../image/CCSF-HM-removebg-preview.png';
import logo4 from '../../image/National-Lottery-removebg-preview.png'
import logo5 from '../../image/City-bridge-trust-removebg-preview.png';
import facebook from '../../image/021-facebook.png';
import instagram from '../../image/025-instagram.png';
import twitter from '../../image/043-twitter.png';
import './News.css';
import cross from '../../image/cross-sign.png';
const News = () => {
function action() {
var action = document.querySelector('.action');
action.classList.toggle('active');
}
return (
<div>
<div className="news-background">
<Navbar></Navbar>
<h1>News & Blogs.</h1>
</div>
<div className="action" onClick={action}>
<span className="text-center">Be part of <br /> Ekota</span>
<div className="popup">
<div className="container ml-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-4">
<h4>Sponsor</h4>
<h3>Ekota Sports</h3>
<small>Be a Member</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Career At</h4>
<h3>Ekota Sports</h3>
<small>Join the team</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Join</h4>
<h3>Ekota Sports</h3>
<small>Be a Volunteer</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
</div>
</div>
<div className="container-fluid subscribe mt-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-8 partner-1">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-2">
<img className="img-fluid "src={logo} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo1} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo2} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo3} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos"src={logo4} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos"src={logo5} alt="" />
</div>
</div>
</div>
<div className="col-md-4 icon ">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-5">
<h6>Follow Us On:</h6>
</div>
<div className="col-md-7">
<img className="img-fluid "src={facebook} alt="" />
<img className="img-fluid "src={instagram} alt="" />
<img className="img-fluid "src={twitter} alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="container ">
<div className="row news d-flex justify-content-center align-items-center">
<div className="col-md-5 news-img">
<img className="img-fluid " src={news} alt="" />
</div>
<div className="col-md-7">
<h2>ISOUL Volunteer’s Training</h2>
<p>
As Ekota Academy approaches the end of the year, we continue to offer a range of programmes and opportunities. One of these is the I Soul Volunteer’s training package, which was delivered, in partnership with the Department for Digital, Culture, Media and Sport and The National Lottery Community Fund.
This fantastic programme involved training several volunteers in leadership, risk management and broader voluntary skills. Those involved have given excellent feedback on this learning opportunity and its impact.
<NAME>, one of the participants, said,” I found it a good course. It was hard at first, but I really enjoyed the chance to meet new people, think about my leadership and learn more about volunteering.”
The programme focused on helping all those involved to develop and strengthen their volunteering skills. The aim was also to use the learning gained to inspire and be a platform for further individual development.
The volunteers will hopefully be working with Ekota on many of our programmes over the next year, so they have been empowered further to confidently work and contribute to our shared goals. Well done to all those involved in the delivery and to those participating!
<br />
<NAME>
<br />
Chair
<br />
Ekota Academy
</p>
</div>
</div>
</div>
{/* <div className="container news1 mt-5">
<div className="row">
<div className="col-md-9">
<div className="row ">
<div className="col-md-12 mb-5 d-flex justify-content-center align-items-center">
<img className="img-fluid " src={news} alt="" />
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci, sunt.</h4>
</div>
<div className="col-md-12 mb-5 d-flex justify-content-center align-items-center">
<img className="img-fluid " src={news} alt="" />
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci, sunt.</h4>
</div>
<div className="col-md-12 mb-5 d-flex justify-content-center align-items-center">
<img className="img-fluid " src={news} alt="" />
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci, sunt.</h4>
</div>
<div className="col-md-12 d-flex justify-content-center align-items-center">
<img className="img-fluid " src={news} alt="" />
<h4>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci, sunt.</h4>
</div>
</div>
</div>
<div className="col-md-3 news2">
<div className="row ">
<div className="col-md-12 mb-5 ">
<img className="img-fluid " src={news} alt="" />
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laborum veritatis neque rerum! Obcaecati praesentium illo officia quos neque dolorum magni nisi. Iure numquam quod veritatis architecto soluta animi consequatur nulla.</p>
</div>
<div className="col-md-12 mb-5 ">
<img className="img-fluid " src={news} alt="" />
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laborum veritatis neque rerum! Obcaecati praesentium illo officia quos neque dolorum magni nisi. Iure numquam quod veritatis architecto soluta animi consequatur nulla.</p>
</div>
<div className="col-md-12 ">
<img className="img-fluid " src={news} alt="" />
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laborum veritatis neque rerum! Obcaecati praesentium illo officia quos neque dolorum magni nisi. Iure numquam quod veritatis architecto soluta animi consequatur nulla.</p>
</div>
</div>
</div>
</div>
</div> */}
<h2 className="text-center mt-5">Popular Posts</h2>
<div className="container news3 mt-5 ">
<div class="row row-cols-1 row-cols-lg-4 row-cols-md-3 g-4">
<div class="col">
<div class="card h-100">
<figure className="image">
<img className="img-fluid " src={image3} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">Developing youngsters</h5>
<p class="card-text">At Ekota Academy, we are dedicated to not only developing sporting prowess, but we try to lead by example at all times. Cricket is only one of many sports we are delivering, and includes, football, running, martial arts. In a short space of time, we have also sent our young players for various trials, and we thrive on engaging </p>
<a href="#" class="news-btn">Read More</a>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<figure className="image">
<img className="img-fluid" src={image} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">Impact of coaching</h5>
<p class="card-text">
A Coach will impact more young people in a year than the average person does in a lifetime!
Our Academy started after we decided to look into providing accessible sports for young people in our locality. We serve our community through sports, but it’s a lot more than just that as we mentor, guide and teach every young person we work with.
</p>
<a href="#" class="news-btn">Read More</a>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<figure className="image">
<img className="img-fluid " src={image2} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">International Women’s Day</h5>
<p class="card-text">International Women’s day is always an important day for Ekota Academy. With our strong female leadership team and focus on empowering women and girls through our work, the day is always a key point of reflection and celebration.
This year we held a virtual webinar, sponsored by Barking and Dagenham Council
</p>
<a href="#" class="news-btn">Read More</a>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<figure className="image">
<img className="img-fluid " src={image1} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">Winning is Infectious!</h5>
<p class="card-text"> Winning is infectious! Mayfield Cup Champions! Well done boys!
At Ekota Academy we coach sports and also mentor, guide and inspire.
We keep the kids busy and sessions are always fun, always vigorous. The idea is they’re too tired afterwards to get up to any hanky panky.
</p>
<a href="#" class="news-btn">Read More</a>
</div>
</div>
</div>
</div>
</div>
<div className="tournament">
<h2>Tournaments</h2>
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<img className="img-fluid " src={image3} alt="" />
</div>
<div className="col-md-6">
<h4>We provide on-ground competitive experience to our students through regular tournaments. To support participants all-round development – installing confidence, increasing concentration, and creating the right mental attitude to play competitive sports – students will have the opportunities to take part in various tournaments throughout the year.
These tournaments will help in enriching a child’s social environment, cultivating key sporting talent, along with shaping the youngster’s leadership, communication, teamwork, and organisational skill sets.
</h4>
</div>
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default News;<file_sep>import React from 'react';
import './testimonial.css';
const testimonial = () => {
return (
<div>
<div className=" testimonial mt-5">
<div className="background">
<div className="description">
<div className="overlays">
.
<h2 className="mb-5">‘’Ekota has helped my child to develop new skills and I can see the week on week physical improvements and he is always excited to attend the sessions.’’</h2>
<p>At Ekota we have not taken a selective approach to those who join our club and football activities. We have encouraged young people with no sporting abilities, varying physical levels and from challenging backgrounds to become involved and participate. This aligns to our central mission statement and approach to maximise participation in sport for all. </p>
<a style={{marginLeft:'20px'}} href="#" className="description-btn mt-3">Express Your Interest</a>
</div>
</div>
</div>
</div>
</div>
);
};
export default testimonial;<file_sep>import React from 'react';
import Footer from '../Footer/Footer';
import Navbar from '../Navbar/Navbar';
import './Youth.css';
const Youth = () => {
return (
<div className="youth ">
<div >
<Navbar></Navbar>
</div>
<div >
<h2>Signposting to other youth services</h2>
<h5 className="ml-5">Ekota is here to support you working in partnership with a range of organisations. Whatever your situation - do contact us or others for help <br /> and to access opportunities. If you need further support, there are a range of services you can access</h5>
</div>
<div className="container">
<div className="row youth-description-row d-flex justify-content-center align-items-center">
<div className="col-md-4">
<h1>"We must equip our youth to thrive in a changing worlds"</h1>
</div>
<div className="col-md-8 d-flex justify-content-center align-items-center youth-card">
<div className="row youth-row">
<div className="col-md-12 youth-description-row">
<div className="row youth-card-row">
<div className="col-md-4">
<div className="square square-one">
<span></span>
<span></span>
<span></span>
<div className="content">
<h3>Barking & Dagenham</h3>
<ul>
<li><a href="https://www.lbbd.gov.uk/youth-offending">Youth Offender Service</a></li>
<li><a href="https://www.lbbd.gov.uk/young-people-and-youth-services">Youth Forum</a></li>
<li><a href="https://www.lbbd.gov.uk/children-young-people-and-families">Children, young people & families</a></li>
</ul>
</div>
</div>
</div>
<div className="col-md-4">
<div className="square">
<span></span>
<span></span>
<span></span>
<div className="content">
<h3>Barking & Dagenham</h3>
<ul>
<li><a href="https://www.futureyouthzone.org/">Youth Center for age 8-19</a></li>
</ul>
</div>
</div>
</div>
<div className="col-md-4">
<div className="square">
<span></span>
<span></span>
<span></span>
<div className="content">
<h3>Barking & Dagenham</h3>
<ul>
<li><a href="https://www.nelft.nhs.uk/barking-and-dagenham-age-11-18/">NHS Foundation Trust</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div className="col-md-12">
<div className="row youth-card-row">
<div className="col-md-4">
<div className="square">
<span></span>
<span></span>
<span></span>
<div className="content">
<h3>Youth Access</h3>
<ul>
<li><a href="https://www.youthaccess.org.uk/">Advice & Counselling Network</a></li>
</ul>
</div>
</div>
</div>
<div className="col-md-4">
<div className="square">
<span></span>
<span></span>
<span></span>
<div className="content">
<h3>Supports Parents cares & individuals</h3>
<ul>
<li><a href="http://www.sycamoretrust.org.uk/">sycamore trust autistic specturm</a></li>
</ul>
</div>
</div>
</div>
<div className="col-md-4">
<div className="square square-one">
<span></span>
<span></span>
<span></span>
<div className="content">
<h3>Young Mind</h3>
<ul>
<li><a href="https://youngminds.org.uk/about-us/">Fighting for young children mental health</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default Youth;<file_sep>import React from 'react';
import Footer from '../Footer/Footer';
import Navbar from '../Navbar/Navbar';
import './Governance.css';
const Governance = () => {
return (
<div>
<div className="governance-bg">
<Navbar></Navbar>
<h1>Governance</h1>
</div>
<div className="football governance-des">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="left3"></div>
<div className="right">
<div className="content">
<h2 className="mb-4">Governance.</h2>
<p className="mb-5">At Ekota we ensure that appropriate governance and safeguarding is in place for the interest of our organisation and the local populations we work with. We have two qualified welfare officers and ensure that DBS checks are undertaken with any volunteers and coaches who work at the club. We have also developed safeguarding and fair play policies, which we share and make available.
</p>
</div>
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default Governance;<file_sep>import React from 'react';
import Navbar from '../../Navbar/Navbar';
import pictures from '../../../image/tSvrnmQSHpIhzlio4mPp51iKhOwA9hNbW5N8wNt63LgeJxFPc.jfif';
import img from '../../../image/MMTOR49NEwvCfEzvuAHuhuwvy4et_p55KiRIx4D9AMUeJxFPc.jfif';
import img1 from '../../../image/1X_u4PD9kdIdelCkR0rAx4aVDWE_wMwBQrgpC_XoeQ8eJxFPc.jfif';
import dynamo from '../../../image/186067240_3820979101333082_1895083144967816894_n.png';
import './Cricket.css';
import Footer from '../../Footer/Footer';
const Cricket = () => {
return (
<div>
<div className="cricket-background">
<Navbar></Navbar>
<h1>Cricket.</h1>
</div>
{/* <div className=" text-center academy">
<div className="row w-100 d-flex justify-content-center align-items-center">
<div className="col-md-7">
<div className="para container">
<h1 style={{ fontWeight: '700', padding: '20px 40px', fontFamily: 'Poppins', fontSize: '50px', textAlign: 'left' }}> Cricket...</h1>
<p>
Ekota offers a range of coaching courses for children of 5-16 years on a weekly basis. Along with special programmes which run during school holidays.
Ekota in collaboration and association with the Essex Cricket Board (ECB) with our exhaustive cricket curriculum aims to develop every aspect of the game, build on existing talent, and create future cricketing stars.
Our students receive extensive coaching and training sessions to develop every aspect of the game – starting from increasing fitness levels through strength and conditioning training to perfecting skills and expertise. Coaches will focus on the strengths and weaknesses of the individual; whether it be batting, bowling, wicket keeping or fielding, and offer the unique opportunity to work on individual areas of improvement in a comfortable environment.
Our year-round training programme includes indoor and outdoor facilities for all.
</p>
</div>
</div>
<div className="col-md-5">
<img style={{ objectFit: 'cover' }} className="img-fluid" src={cricket} alt="" />
</div>
</div>
</div> */}
<div className="all-star">
<div className="container">
<div className="row all-star d-flex justify-content-center align-items-center">
<div className="col-md-7">
<img src={dynamo} alt="" />
</div>
<div className="col-md-5 content">
<h2>All-Stars and Dynamo Cricket programme ( April-August): </h2>
<h5>All-Stars Cricket and Dymano Cricket are the England and Wales Cricket Board’s entry-level participation programmes, aimed at providing children aged five to twelve with a great first experience in cricket.</h5>
<p>
Programme features:
<ul>
<li> For all boys and girls aged five to twelve </li>
<li> Eight one-hour sessions, held over eight weeks</li>
<li> Emphasis on fun and being active</li>
<li> Focus on developing your child's movement skills</li>
<li> Safe and fully accredited</li>
<li> Valuable time with your kids – mums, dads and guardians are encouraged to take part too </li>
<li> Easy online registration </li>
<li> Includes a bonus pack of personalised cricket kit</li>
</ul>
</p>
<h5>In addition every child that registers for the All Stars programme will receive a backpack full of goodies including a cricket bat, ball, personalised shirt and cap all sent straight to your door.
By registering for All Stars and Dynamo Cricket, your child will be guaranteed eight weeks of jam-packed fun, activity and skills development. The programme is suitable for all children new to cricket and sport as the sessions are designed to teach the basic skills of the game.
</h5>
</div>
</div>
</div>
</div>
<div className="girls-cricket">
<div className="girl">
<h4>Female led and Girls only sessions </h4>
<p>Ekota has developed girls only sessions to provide focussed development opportunities for our female participants. These sessions are led by our all female ECB trained coaches who share their expertise, provide a supportive environment and provide positive role models to those who attend.
</p>
</div>
</div>
<div className="foundation-cricket">
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<figure className="image">
<img className="img-fluid " src={pictures} alt="" />
</figure>
</div>
<div className="col-md-6">
<h3>Foundation Programme</h3>
<p>Building up from the All-Star programme we aim to provide children aged five to ten with a great foundation to develop their experience in cricket. The course designed to provide a basic introduction to the game of cricket, focusing on developing movement and skills needed for becoming a cricketer. Along with developing skills such as running, jumping, hand-eye coordination, catching, throwing and hitting, social skills such as listening, concentration and observation are also harnessed.</p>
<a href="#" class="btn">Express Your Interest</a>
</div>
</div>
</div>
</div>
<div className="foundation-cricket">
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6 foundations">
<h3>Intermediate programme</h3>
<p>The course focuses on developing the all-round cricketing skills of the youngsters with the help of extensive coaching sessions. The tailored course aids students to gain expertise in catching, throwing, bowling, along with practising at the net and with the batting-bowling machine. The course intends to fine-tune the cricketing skills of the students with the group as well as one-on-one coaching sessions. The students are also provided with the option of playing tournaments and representing the academy through various activities & tours.</p>
<a href="#" class="btn">Express Your Interest</a>
</div>
<div className="col-md-6">
<figure className="image">
<img className="img-fluid " src={img} alt="" />
</figure>
</div>
</div>
</div>
</div>
<div className="female">
<div className="girl">
<h3>Cricket For Girls</h3>
<p>Ekota academy encourages and provides empowering sporting experience for girls from the grassroots level.</p>
</div>
</div>
<div className="foundation-cricket">
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<figure className="image">
<img className="img-fluid " src={img1} alt="" />
</figure>
</div>
<div className="col-md-6">
<h3>Advance Programme</h3>
<p> Building on the foundation and developing programme, this programme is designed to accelerate players through high-quality, structured coaching sessions designed to challenge the participants so that they can improve their skills.
These games are based on learning, testing on psychology and decision making, strength and conditioning, communication and leadership. Building upon the experiences, giving knowledge, skills and confidence to help individuals improve their game as well as developing a wide area of expertise on working within teams.
</p>
<a href="#" class="btn">Express Your Interest</a>
</div>
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default Cricket;<file_sep>import React from 'react';
import Footer from '../Footer/Footer';
import Navbar from '../Navbar/Navbar';
import facebook from '../../image/021-facebook.png';
import twitter from '../../image/043-twitter.png';
import instagram from '../../image/025-instagram.png';
import logo from '../../image/Sport-England-Logo-Blue-(CMYK).png';
import logo1 from '../../image/Eagles_in_the_Community_Logo_2018_1-removebg-preview.png';
import logo2 from '../../image/Vision Logo 2018 FINAL transparent.png';
import logo3 from '../../image/CCSF-HM-removebg-preview.png';
import logo4 from '../../image/National-Lottery-removebg-preview.png'
import logo5 from '../../image/City-bridge-trust-removebg-preview.png';
import join from '../../image/360_F_269423667_XHYPqqocezmCuFvWbRjdhZWtIP1kbNTy-removebg-preview.png';
import './Contact.css';
import cross from '../../image/cross-sign.png';
const Contact = () => {
function action() {
var action = document.querySelector('.action');
action.classList.toggle('active');
}
return (
<div>
<div className="contact-navbar">
<Navbar></Navbar>
<h1>Contact Us.</h1>
</div>
<div className="action" onClick={action}>
<span className="text-center">Be part of <br /> Ekota</span>
<div className="popup">
<div className="container ml-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-4">
<h4>Sponsor</h4>
<h3>Ekota Sports</h3>
<small>Be a Member</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Career At</h4>
<h3>Ekota Sports</h3>
<small>Join the team</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Join</h4>
<h3>Ekota Sports</h3>
<small>Be a Volunteer</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
</div>
</div>
<div className="container-fluid subscribe mt-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-8 partner-1">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-2">
<img className="img-fluid "src={logo} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo1} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo2} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo3} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos "src={logo4} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos "src={logo5} alt="" />
</div>
</div>
</div>
<div className="col-md-4 icon ">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-5">
<h6>Follow Us On:</h6>
</div>
<div className="col-md-7">
<img className="img-fluid "src={facebook} alt="" />
<img className="img-fluid "src={instagram} alt="" />
<img className="img-fluid "src={twitter} alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="contact">
<div className="staff contact-join">
<h3> Join us - Become a volunteer </h3>
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<div className="">
<p className="mb-5">
We are seeking people to get involved from a wide range of backgrounds to be part of the diverse Ekota family. This is a chance to be a part of a social movement working with an experienced and passionate team.
Become a volunteer today and gain new skills, meet new people, support and give back to your local community. Our opportunities can also help those individuals seeking paid employment to build up their confidence and skills.
You must be 16 years and above with no criminal convictions. All volunteers will be required to complete a DBS check. You will receive a range of relevant training and support to deliver your role.
</p>
</div>
</div>
<div className="col-md-6">
<img className="img-fluid "src={join} alt="" />
</div>
</div>
</div>
</div>
{/* <div className="container">
<h2>Signposting to other <span style={{ color: '#e15430' }}>youth</span> services </h2>
<p>Ekota is here to support you working in partnership with a range of organisations. Whatever your situation - do contact us or others for help and to access opportunities. If you need further support, there are a range of services you can access</p>
</div> */}
<div className="container ">
<div className="row date-events d-flex justify-content-center align-items-center">
<div className="col-md-6 col-sm-6">
<div className="boxs">
<div className="box_contents">
<input type="text" placeholder="Your Name" required="required" />
<br />
<input type="text" placeholder="Your Email" required="required" />
<br />
<input type="text" placeholder="Your Question" required="required" />
<br />
<textarea placeholder="Message"></textarea>
</div>
<div className="btn-news">
<a href="#" className="btn1">Submit</a>
</div>
</div>
</div>
</div>
</div>
</div>
{/* <div className="testimonials coach text-center ">
<div className="container">
<div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<h1>‘’</h1>
<p>‘’Ekota has helped my child to develop new skills and I can see the week on week physical improvements and he is always excited to attend the sessions.’’</p>
<h4><NAME></h4>
<h6>Coach</h6>
</div>
<div class="carousel-item">
<h1>‘’</h1>
<p>‘’Ekota has helped my child to develop new skills and I can see the week on week physical improvements and he is always excited to attend the sessions.’’</p>
<h4><NAME></h4>
<h6>Coach</h6>
</div>
<div class="carousel-item">
<h1>‘’</h1>
<p>‘’Ekota has helped my child to develop new skills and I can see the week on week physical improvements and he is always excited to attend the sessions.’’</p>
<h4><NAME></h4>
<h6>Coach</h6>
</div>
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</div>
</div> */}
{/* <div className="sponsorship">
<div className="container">
<div className="row">
<div className="col-md-4">
<img className="img-fluid " src={logo} alt="" />
</div>
<div className="col-md-4 logo1">
<img className="img-fluid " src={logo2} alt="" />
</div>
<div className="col-md-4 logo1">
<img className="img-fluid " src={logo1} alt="" />
</div>
</div>
</div>
</div> */}
<Footer></Footer>
</div>
);
};
export default Contact;<file_sep>import React from 'react';
import Navbar from '../../Navbar/Navbar';
import './Join.css';
import Footer from '../../Footer/Footer';
import facebook from '../../../image/021-facebook.png';
import instagram from '../../../image/025-instagram.png';
import twitter from '../../../image/043-twitter.png';
import cross from '../../../image/cross-sign.png';
import logo from '../../../image/Sport-England-Logo-Blue-(CMYK).png';
import logo1 from '../../../image/Eagles_in_the_Community_Logo_2018_1-removebg-preview.png';
import logo2 from '../../../image/Vision Logo 2018 FINAL transparent.png';
import logo3 from '../../../image/CCSF-HM-removebg-preview.png';
import logo4 from '../../../image/National-Lottery-removebg-preview.png'
import logo5 from '../../../image/City-bridge-trust-removebg-preview.png';
import { Link } from 'react-router-dom';
import Cricket from './Cricket';
const Join = () => {
function action() {
var action = document.querySelector('.action');
action.classList.toggle('active');
}
return (
<div>
<div className="join">
<Navbar></Navbar>
<h1>Sports.</h1>
</div>
<div className="main-section">
<p>Ekota believes in the power of sport and works to help individuals to get healthy, <br /> connect with others, as well as helping to develop the next generation of sporting stars. <br /> Our expert coaches will help everyone find their true potential .</p>
</div>
<div className="action" onClick={action}>
<span className="text-center">Be part of <br /> Ekota</span>
<div className="popup">
<div className="container ml-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-4">
<h4>Sponsor</h4>
<h3>Ekota Sports</h3>
<small>Be a Member</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Career At</h4>
<h3>Ekota Sports</h3>
<small>Join the team</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Join</h4>
<h3>Ekota Sports</h3>
<small>Be a Volunteer</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
</div>
</div>
<div className="container-fluid subscribe mt-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-8 partner-1">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-2">
<img className="img-fluid "src={logo} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo1} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo2} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo3} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos"src={logo4} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos"src={logo5} alt="" />
</div>
</div>
</div>
<div className="col-md-4 icon ">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-5">
<h6>Follow Us On:</h6>
</div>
<div className="col-md-7">
<img className="img-fluid "src={facebook} alt="" />
<img className="img-fluid "src={instagram} alt="" />
<img className="img-fluid "src={twitter} alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="football footballs">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="left"></div>
<div className="right">
<div className="content">
<h3>Football.</h3>
<p>Ekota FC has been running Saturday clubs from 2014 in Goodmayes Park. We provide an opportunity for children to improve their skills and be a part of a competitive football team.Children from ages 5-16 of all abilities are welcome to join our weekly training sessions. The club is registered with the FA and the sessions are being facilitated by FA qualified coaches.</p>
<a href="#" class="discover-btn " data-bs-toggle="modal" data-bs-target="#exampleModal">Read More</a>
</div>
</div>
<div style={{ fontFamily: 'Poppins' }} class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Football</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Ekota FC has been running Saturday clubs from 2014 in Goodmayes Park. We provide an opportunity for children to improve their skills and be a part of a competitive football team.Children from ages 5-16 of all abilities are welcome to join our weekly training sessions. The club is registered with the FA and the sessions are being facilitated by FA qualified coaches.
Sessions are taught in small groups based on age and ability. During the session, participants will undertake drills, improve their fitness and play matches. The aim is to help improve footballing, fitness and social skills.
We aim to provide a friendly environment, which motivates participants but also gives them a framework to grow and develop.
The club has developed strong networks with other football teams and organisations to provide additional opportunities for our club members.
All those involved in the organisation including parents and players are expected to follow the code of conduct and failure to do adhere to the terms will not be accepted.
</div>
<div class="modal-footer">
<Link to='/football'> <button class="discover-btn" type="button" data-bs-dismiss="modal">Discover More</button></Link>
{/* <a href="#" class="discover-btn ">Discover More</a>> */}
</div>
</div>
</div>
</div>
</div>
</div>
{/* <div className="cricket">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="right1">
<div className="content">
<h3>Cricket.</h3>
<p className="mb-5">Ekota aims to teach future cricketers new skills and to give them the very best first experience in the world of cricket. A chance to play, learn great skills and meet new friends!
Ekota cricket programmes are designed for players wanting to get that competitive edge over their opponents. It is a high intense and structured program ensuring all facets of batting, bowling, and fielding are covered and that all players gain some more knowledge about becoming a cricket maestro.
</p>
<Link to='/cricket'> <a href="#" class="discover-btn">Discover More</a></Link>
</div>
</div>
<div className="left1"></div>
</div>
</div> */}
<Cricket></Cricket>
<div className="football footballs" id="martial">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="martial-arts"></div>
<div className="right">
<div className="content">
<h3>Martial Arts.</h3>
<p>Ekota FC has been running Saturday clubs from 2014 in Goodmayes Park. We provide an opportunity for children to improve their skills and be a part of a competitive football team.Children from ages 5-16 of all abilities are welcome to join our weekly training sessions. The club is registered with the FA and the sessions are being facilitated by FA qualified coaches.</p>
</div>
</div>
</div>
</div>
<div className="cricket footballs" id="badminton">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="right1">
<div className="content">
<h3>Badminton.</h3>
<p className="mb-5">Ekota aims to teach future cricketers new skills and to give them the very best first experience in the world of cricket. A chance to play, learn great skills and meet new friends!
Ekota cricket programmes are designed for players wanting to get that competitive edge over their opponents. It is a high intense and structured program ensuring all facets of batting, bowling, and fielding are covered and that all players gain some more knowledge about becoming a cricket maestro.
</p>
</div>
</div>
<div className="badminton"></div>
</div>
</div>
<div className="football footballs " id="walking">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="walking"></div>
<div className="right">
<div className="content">
<h3>Walking Cricket</h3>
<p>Ekota Academy is now offering free sessions on Walking Cricket in Goodmayes Park!
Walking Cricket is a slower version of the traditional game played at walking pace with adapted rules and has been specially designed for people that love the game of cricket but can no longer play the traditional version due to:
<br />
Age
<br />
Medical conditions
<br />
Inactivity
<br />
Disabilities
<br />
Recovery/ rehabilitation from medical operations
<br />
Social isolation and loneliness
<br />
Inability to play the traditional game for any other reason.
</p>
</div>
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default Join;<file_sep>import React from 'react';
import pictures from '../../image/1X_u4PD9kdIdelCkR0rAx4aVDWE_wMwBQrgpC_XoeQ8eJxFPc.jfif';
import pictures1 from '../../image/27Yoy53ty915jjw2-4k43pqxxnoxY7dTcoHg8zM6SI0eJxFPc.jfif';
import pictures2 from '../../image/WlHzIft4vXCIj0hAebsU-4VivWE-w-eTwFB8qb1gevYeJxFPc.jfif';
import pictures3 from '../../image/ZQgXhC84UabKkGfmeXpsDnR3q8jBok0ZJIJUkXQ86FoeJxFPc (1).jfif';
import pictures4 from '../../image/w29AnzRvddYhL8qZM_tAO2mzE62pRWHp-AdFzPYC70seJxFPc.jfif';
import pictures5 from '../../image/tSvrnmQSHpIhzlio4mPp51iKhOwA9hNbW5N8wNt63LgeJxFPc.jfif';
import { Link} from 'react-router-dom';
import './Gallery.css';
const Gallery = () => {
const scrollToTop = () => {
window.scrollTo(0, 0)
}
return (
<div className="gallery">
<div className="container">
<div className="row row-cols-md-4 row-cols-1">
<div className="col">
<Link to='/gallery'>
<div onclick={scrollToTop} className="card">
<img src={pictures} alt="" />
</div>
</Link>
</div>
<div className="col">
<Link to='/gallery'>
<div className="card">
<img src={pictures1} alt="" />
</div>
</Link>
</div>
<div className="col">
<Link to='/gallery'>
<div className="card">
<img src={pictures2} alt="" />
</div>
</Link>
</div>
<div className="col">
<div className="card">
<img src={pictures3} alt="" />
</div>
</div>
</div>
</div>
</div>
);
};
export default Gallery;<file_sep>import React from 'react';
import './Banner.css';
import {Link} from 'react-router-dom';
const Banner = () => {
return (
<div className="banner ">
<div className="background">
<div className="description">
.
<h1>Free Trial</h1>
<Link to='/contact'> <a href="#" className="btn btn-danger">Book Now</a></Link>
</div>
</div>
</div>
);
};
export default Banner;<file_sep>import React from 'react';
import Footer from '../../Footer/Footer';
import Navbar from '../../Navbar/Navbar';
import facebook from '../../../image/021-facebook.png';
import instagram from '../../../image/025-instagram.png';
import twitter from '../../../image/043-twitter.png';
import pictures from '../../../image/WhatsApp Image 2021-07-07 at 11.23.27.jpeg';
import seal from '../../../image/seal-01.png';
import logo from '../../../image/Sport-England-Logo-Blue-(CMYK).png';
import logo1 from '../../../image/Eagles_in_the_Community_Logo_2018_1-removebg-preview.png';
import logo2 from '../../../image/Vision Logo 2018 FINAL transparent.png';
import logo3 from '../../../image/CCSF-HM-removebg-preview.png';
import logo4 from '../../../image/National-Lottery-removebg-preview.png'
import logo5 from '../../../image/City-bridge-trust-removebg-preview.png';
import team from '../../../image/kugghjul-removebg-preview.png';
import staff from '../../../image/staffmanagement1-removebg-preview.png';
import volunteer from '../../../image/19-196805_volunteer-icon-logo-become-a-volunteer-hd-png-removebg-preview.png';
import join from '../../../image/360_F_269423667_XHYPqqocezmCuFvWbRjdhZWtIP1kbNTy-removebg-preview.png';
import emdad from '../../../image/WhatsApp Image 2021-08-01 at 6.59.57 PM.jpeg';
import cross from '../../../image/cross-sign.png';
import './Club.css';
const Club = () => {
function action() {
var action = document.querySelector('.action');
action.classList.toggle('active');
}
return (
<div className="club-background">
<div>
<Navbar></Navbar>
<h1>Team.</h1>
</div>
<div className="management" id="management">
<h3 className="mb-5"> Our Team, Management & Governance.</h3>
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<img className="img-fluid " src={team} alt="" />
</div>
<div className="col-md-6">
<div className="">
<p className="mb-5">Our team has a range of expertise and backgrounds with a track record of successful delivery of projects. The existing team is made up of 3 trustees, a chief officer, consultants and a number of coaches in their speciality of the field who work for the club. At Ekota we are proud that our central team involves a strong group of female leaders, which is a reflection on the nature and values of the organisation.
In addition, Ekota is also bringing in female coaches to provide expertise, encourage more female participation and positive role modelling.
We would also work in partnership with a range of organisations such as the England Cricket Board, Essex cricket club, the Football Association, Sports England, local schools and local authorities.
</p>
</div>
</div>
</div>
</div>
</div>
<div className="action" onClick={action}>
<span className="text-center">Be part of <br /> Ekota</span>
<div className="popup">
<div className="container ml-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-4">
<h4>Sponsor</h4>
<h3>Ekota Sports</h3>
<small>Be a Member</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Career At</h4>
<h3>Ekota Sports</h3>
<small>Join the team</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
<div className="col-md-4">
<h4>Join</h4>
<h3>Ekota Sports</h3>
<small>Be a Volunteer</small>
<div className="action">
<span> <img className="cross" src={cross} alt="" /> </span>
</div>
</div>
</div>
</div>
<div className="container-fluid subscribe mt-5">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-8 partner-1">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-2">
<img className="img-fluid "src={logo} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo1} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo2} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid "src={logo3} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos "src={logo4} alt="" />
</div>
<div className="col-md-2">
<img className="img-fluid logos"src={logo5} alt="" />
</div>
</div>
</div>
<div className="col-md-4 icon ">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-5">
<h6>Follow Us On:</h6>
</div>
<div className="col-md-7">
<img className="img-fluid "src={facebook} alt="" />
<img className="img-fluid "src={instagram} alt="" />
<img className="img-fluid "src={twitter} alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="staff">
<h3>Staff & Management.</h3>
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<div className="">
<p className="mb-5"> All of our coaches are fully qualified in their relevant field of expertise and have been through the appropriate training and checks required for their role.
The Club has two Welfare Officer (Male & Female) who are responsible for ensuring that the club follows its responsibilities in running activities for children, supporting the staff to understand their duty of care, ensuring policies are in place – understood communicated and followed. The Welfare Officer also helps to monitor and encourage good practice and acts as a point of contact for staff, children or parents for any concerns.
If you would like to contact the Welfare Officer please email: <EMAIL>
</p>
</div>
</div>
<div className="col-md-6">
<img className="img-fluid "src={staff} alt="" />
</div>
</div>
</div>
</div>
<div className="staff" id="volunteer">
<h3> Join us - Become a volunteer </h3>
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6">
<div className="">
<p className="mb-5">
We are seeking people to get involved from a wide range of backgrounds to be part of the diverse Ekota family. This is a chance to be a part of a social movement working with an experienced and passionate team.
Become a volunteer today and gain new skills, meet new people, support and give back to your local community. Our opportunities can also help those individuals seeking paid employment to build up their confidence and skills.
You must be 16 years and above with no criminal convictions. All volunteers will be required to complete a DBS check. You will receive a range of relevant training and support to deliver your role.
</p>
</div>
</div>
<div className="col-md-6">
<img className="img-fluid "src={join} alt="" />
</div>
</div>
</div>
</div>
<div className="staff">
<h3>Volunteers.</h3>
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-6 volunteer-img">
<img className="img-fluid " src={volunteer} alt="" />
</div>
<div className="col-md-6">
<div className="">
<p className="mb-5">
All our volunteers will have to go through a process of recruitment and checks will be undertaken. If you are interested in volunteering with the club please complete the Ekota_volunteer_application and email it to <EMAIL>
</p>
</div>
</div>
</div>
</div>
</div>
<div className="teams">
<h2 className="container-fluid mb-5">Meet Our Coaches</h2>
<div className="container text-center">
<div className="row">
<div className="col-md-4 col-sm-6">
<div className="box">
<div className="avatar">
<img className="img-fluid " src={pictures} alt="" />
</div>
<div className="box_content">
<h3 className="title"><NAME></h3>
<span className="post">Head Coach</span>
</div>
<ul className="icons-social">
<li><a href="#"><img className="img-fluid img" src={facebook} alt="" /></a></li>
<li><a href="#"><img className="img-fluid img" src={instagram} alt="" /></a></li>
<li><a href="#"><img className="img-fluid img" src={twitter} alt="" /></a></li>
</ul>
</div>
</div>
<div className="col-md-4 col-sm-6">
<div className="box">
<div className="avatar">
<img className="img-fluid " src={emdad} alt="" />
</div>
<div className="box_content">
<h3 className="title"><NAME></h3>
<span className="post">football Coach</span>
</div>
<ul className="icons-social">
<li><a href="#"><img className="img-fluid img" src={facebook} alt="" /></a></li>
<li><a href="#"><img className="img-fluid img" src={instagram} alt="" /></a></li>
<li><a href="#"><img className="img-fluid img" src={twitter} alt="" /></a></li>
</ul>
</div>
</div>
<div className="col-md-4 col-sm-6">
<div className="box">
<div className="avatar">
<img className="img-fluid " src={pictures} alt="" />
</div>
<div className="box_content">
<h3 className="title"><NAME></h3>
<span className="post">Head Coach</span>
</div>
<ul className="icons-social">
<li><a href="#"><img className="img-fluid img" src={facebook} alt="" /></a></li>
<li><a href="#"><img className="img-fluid img" src={instagram} alt="" /></a></li>
<li><a href="#"><img className="img-fluid img" src={twitter} alt="" /></a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
{/* <div className="news">
<h3>News & Events</h3>
<div className="container mt-5">
<div class="row container row-cols-1 row-cols-md-3 g-4">
<div class="col">
<div class="card h-100">
<figure className="image">
<img src={pictures} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">New Tournament</h5>
<p class="card-text">The indoor tournament, activities and food were enjoyed by all. Prizes were given to the successful teams and recognition was given for individual efforts across the season.</p>
<a href="#" class="btn btn-danger">Read More</a>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<figure className="image">
<img src={pictures} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">The Indoor Tournament</h5>
<p class="card-text">It was a successful event which brought the community together to connect and celebrate our achievements. You can see the pictures from the day in our gallery</p>
<a href="#" class="btn btn-danger">Read More</a>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<figure className="image">
<img src={pictures} class="card-img-top" alt="..." />
</figure>
<div class="card-body">
<h5 class="card-title">Latest Events</h5>
<p class="card-text">Thank you to everyone who attended the Ekota Active New Year Event on the 7th February 2015 – Over a hundred parents and children attended. .</p>
<a href="#" class="btn btn-danger">Read More</a>
</div>
</div>
</div>
</div>
</div>
</div> */}
<Footer></Footer>
</div>
);
};
export default Club;<file_sep>import React from 'react';
import { Link } from 'react-router-dom';
import { Modal } from 'react-bootstrap';
const Cricket = () => {
function MyVerticallyCenteredModal(props) {
return (
<Modal
{...props}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title style={{fontFamily: 'Poppins', fontWeight:'600' }} id="contained-modal-title-vcenter">
Cricket
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p style={{fontFamily: 'Poppins', fontWeight:'500' }}>
Ekota aims to teach future cricketers new skills and to give them the very best first experience in the world of cricket. A chance to play, learn great skills and meet new friends!
Ekota cricket programmes are designed for players wanting to get that competitive edge over their opponents. It is a high intense and structured program ensuring all facets of batting, bowling, and fielding are covered and that all players gain some more knowledge about becoming a cricket maestro.
Ekota offers a range of coaching courses for children of 5-16 years on a weekly basis. Along with special programmes which runduring school holidays.
Ekota in collaboration and association with the Essex Cricket Board (ECB) with our exhaustive cricket curriculum aims to develop every aspect of the game, build on existing talent, and create future cricketing stars.
Our students receive extensive coaching and training sessions to develop every aspect of the game – starting from increasing fitness levels through strength and conditioning training to perfecting skills and expertise. Coaches will focus on the strengths and weaknesses of the individual; whether it be batting, bowling, wicket keeping or fielding, and offer the unique opportunity to work on individual areas of improvement in a comfortable environment.
Our year-round training programme includes indoor and outdoor facilities for all.
</p>
</Modal.Body>
<Modal.Footer>
<Link to='/cricket'>
<a style={{textDecoration: 'none'}} className="discover-btn" href='#'>Discover More</a>
</Link>
</Modal.Footer>
</Modal>
);
}
const [modalShow, setModalShow] = React.useState(false);
return (
<div>
<div className="cricket footballs">
<div style={{ margin: '0', padding: '0', boxSizing: 'border-box' }} className="container containers" id="section">
<div className="right1">
<div className="content">
<h3>Cricket.</h3>
<p className="mb-5">Ekota aims to teach future cricketers new skills and to give them the very best first experience in the world of cricket. A chance to play, learn great skills and meet new friends!
Ekota cricket programmes are designed for players wanting to get that competitive edge over their opponents. It is a high intense and structured program ensuring all facets of batting, bowling, and fielding are covered and that all players gain some more knowledge about becoming a cricket maestro.
</p>
<a href="#" onClick={() => setModalShow(true)} class="discover-btn " >Read More</a>
</div>
</div>
<div className="left1"></div>
</div>
<MyVerticallyCenteredModal
show={modalShow}
onHide={() => setModalShow(false)}
></MyVerticallyCenteredModal>
</div>
</div>
);
};
export default Cricket;<file_sep>import React from 'react';
import Navbar from '../../Navbar/Navbar';
import pictures from '../../../image/hc8rhiIVhocyf4AFOZ3kfmePi0u-EdJ17HhLrZdUeU4eJxFPc.jfif';
import pictures1 from '../../../image/_6eXHo5z9xPNbksmoSg59VGOOgJti88zwJlE0ko3TzoeJxFPc.jfif';
import pictures2 from '../../../image/MZgeGYnnxdc73At89dvvAAvrDl2EVQ7GtrVsPPP1Ja4eJxFPc.jfif';
import './Football.css';
import Footer from '../../Footer/Footer';
const Football = () => {
return (
<div>
<div className="navbar_background">
<Navbar></Navbar>
<h1>Football.</h1>
</div>
<div className="foundation">
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-5">
<figure className="images">
<img className="img-fluid " src={pictures} alt="" />
</figure>
</div>
<div className="col-md-7 foundation1">
<h3>Foundation Programme.</h3>
<p>
This course is designed to make the participants very first experience of football training an enjoyable one. The aim is to keep it exciting, rewarding and fun for the children.
This is designed to provide a basic introduction to the game of football, focusing on developing the movement and skills needed for becoming a footballer. Fair play, team spirit and discipline are just a few of the many values taught during these sessions.
</p>
<a href="#" class="btn">Express Your Interest</a>
</div>
</div>
</div>
</div>
<div className="foundation">
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-7">
<h3>Intermediate programme. </h3>
<p>
This course focuses on developing the all-round footballing skills of participants with the help of extensive coaching sessions. The tailored course aids students to develop their footballing skills further including team working, leadership and communication.
The course intends to fine-tune the footballing skills of the students on a group basis as well as one-on-one coaching sessions. The students are also provided with the option of playing tournaments and representing the academy through various activities and tours.
</p>
<a href="#" class="btn">Express Your Interest</a>
</div>
<div className="col-md-5">
<figure className="images">
<img className="img-fluid " src={pictures1} alt="" />
</figure>
</div>
</div>
</div>
</div>
<div className="foundation">
<div className="container">
<div className="row d-flex justify-content-center align-items-center">
<div className="col-md-5">
<figure className="images">
<img className="img-fluid " src={pictures2} alt="" />
</figure>
</div>
<div className="col-md-7 foundation1">
<h3>Advance Programme.</h3>
<p>
Building on the foundation and intermediate programme this course is designed to accelerate players through high-quality, structured coaching sessions designed to challenge participants.
We scaffold a player's learning process, to create intelligent footballers. Player’s will be exposed to coordination, strength and agility work, tested cognitively and challenged with specific game-related exercises.
</p>
<a href="#" class="btn">Express Your Interest</a>
</div>
</div>
</div>
</div>
<Footer></Footer>
</div>
);
};
export default Football; | 56ffa187dadeaabacf82b89d644bbd69f85a8cd0 | [
"JavaScript"
] | 16 | JavaScript | ShohanShabbir/ekotasports | 8cc4fd6e726ab644ebade13bef54d2b883f26db3 | baccbe928d34d604b5dc1b855cbe54cd6f828b40 | |
refs/heads/master | <repo_name>MedoWaleed07/SilkRoad_culture_platform<file_sep>/settings.gradle
include ':app'
rootProject.name='Research'
<file_sep>/app/src/main/java/com/example/research/Activites/MainActivity.java
package com.example.research.Activites;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.research.CustomProgress;
import com.example.research.Models.FileModel;
import com.example.research.R;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
boolean internet_test;
ImageView language;
ArrayAdapter<CharSequence> adapter,dialog_adapter;
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
DividerItemDecoration dividerItemDecoration;
DataAdapter dataAdapter;
Spinner category_select,dialog_Spinner;
FloatingActionButton add_btn;
List<FileModel> files;
Uri fileUri;
String fileName, fileDate, id, fileURL, extension,category,getByCategory = "AllFiles";
String deleteID;
int fileType;
FileModel fileToDB;
long downloadID;
String lng_status = "en";
FirebaseStorage storage;
StorageReference storageReference;
FirebaseAuth auth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
CustomProgress customProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
internet_test = checkConnection(getApplicationContext());
if (internet_test == false) {
Toast.makeText(this, "Please check your Internet connection", Toast.LENGTH_LONG).show();
return;
}
lng_status = getIntent().getStringExtra("lng_status");
initView();
initFireBase();
getFiles();
customizeDownloader();
if(!user.getEmail().equals("<EMAIL>")){
add_btn.setVisibility(View.INVISIBLE);
add_btn.setEnabled(false);
}else{
add_btn.setVisibility(View.VISIBLE);
add_btn.setEnabled(true);
}
category_select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
getFiles();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void customizeDownloader() {
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long broadcastedDownloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (broadcastedDownloadID == downloadID) {
if (getDownloadStutus() == DownloadManager.STATUS_SUCCESSFUL) {
Toast.makeText(context, "Download Complete.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Download not Complete", Toast.LENGTH_SHORT).show();
}
}
}
}, filter);
}
private int getDownloadStutus(){
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadID);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Cursor cursor = downloadManager.query(query);
if(cursor.moveToFirst()){
int colomnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int stutus = cursor.getInt(colomnIndex);
return stutus;
}
return DownloadManager.ERROR_UNKNOWN;
}
private void getFiles() {
databaseReference.child("Files").child(checkCategory()).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
files.clear();
for(DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
FileModel fileModel = dataSnapshot1.getValue(FileModel.class);
if(fileModel.getFileExtension().equals("docx")|| fileModel.getFileExtension().equals("doc")|| fileModel.getFileExtension().equals("txt")){
fileModel.setDataType(R.drawable.ic_word);
}else if(fileModel.getFileExtension().equals("ppt")){
fileModel.setDataType(R.drawable.ic_powerpoint);
}else if(fileModel.getFileExtension().equals("pdf")){
fileModel.setDataType(R.drawable.ic_pdf);
}else if(fileModel.getFileExtension().equals("xls") || fileModel.getFileExtension().equals("xlsx")){
fileModel.setDataType(R.drawable.ic_excel);
}else if(fileModel.getFileExtension().equals("zip")){
fileModel.setDataType(R.drawable.ic_rar);
}else{
fileModel.setDataType(R.drawable.ic_insert_drive_file_black_24dp);
}
files.add(fileModel);
}
dataAdapter = new DataAdapter(files);
recyclerView.setAdapter(dataAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public String checkCategory(){
if(category_select.getSelectedItem().equals("All") || category_select.getSelectedItem().equals("所有")){
getByCategory = "AllFiles";
}else if(category_select.getSelectedItem().equals("Chinese Literature")|| category_select.getSelectedItem().equals("中国文学")){
getByCategory = "Chinese Literature";
}else if(category_select.getSelectedItem().equals("Chinese linguistics")|| category_select.getSelectedItem().equals("汉语语言学")){
getByCategory = "Chinese linguistics";
}else if(category_select.getSelectedItem().equals("Chinese culture")|| category_select.getSelectedItem().equals("中华文化")){
getByCategory = "Chinese culture";
}else if(category_select.getSelectedItem().equals("Translation ch~Ar")|| category_select.getSelectedItem().equals("阿汉汉阿翻译")){
getByCategory = "Translation ch~Ar";
}else if(category_select.getSelectedItem().equals("News room")|| category_select.getSelectedItem().equals("头条")){
getByCategory = "News room";
}
return getByCategory;
}
private void initFireBase() {
storage = FirebaseStorage.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
auth = FirebaseAuth.getInstance();
}
private void initView() {
recyclerView = findViewById(R.id.recyclerview);
dividerItemDecoration = new DividerItemDecoration(getApplicationContext(),DividerItemDecoration.VERTICAL);
layoutManager = new LinearLayoutManager(getApplicationContext(),RecyclerView.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
files = new ArrayList<>();
add_btn = findViewById(R.id.add_btn);
language = findViewById(R.id.language);
customProgress = CustomProgress.getInstance();
category_select = findViewById(R.id.category);
if (lng_status == null) {
lng_status = "en";
adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.English_Types, android.R.layout.simple_spinner_item);
}else if(lng_status.equals("en")){
adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.English_Types, android.R.layout.simple_spinner_item);
language.setImageResource(R.drawable.ic_chinese_language);
}else if(lng_status.equals("ch")){
adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.Chinese_Types, android.R.layout.simple_spinner_item);
language.setImageResource(R.drawable.ic_english_language);
}
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
category_select.setAdapter(adapter);
}
public void add(View view) {
if (internet_test == false) {
Toast.makeText(this, "Check Your Connection First", Toast.LENGTH_LONG).show();
return;
}
String[] mimeTypes =
{"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip",
"application/rar"};
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
}
startActivityForResult(Intent.createChooser(intent,"ChooseFile"), 1000);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data == null){
Toast.makeText(this, "Please Choose A file", Toast.LENGTH_SHORT).show();
return;
}
switch (requestCode) {
case 1000:
if (resultCode == RESULT_OK) {
fileUri = data.getData();
//************Get File Name*****************
if (fileUri.getScheme().equals("file")) {
fileName = fileUri.getLastPathSegment();
} else {
Cursor cursor = null;
try {
cursor = getContentResolver().query(fileUri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
//***********Get File Date****************
fileDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
//***********Get File Extension***********
String uri = fileName;
extension = uri.substring(uri.lastIndexOf(".") + 1);
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Select Category");
Button dialogButton = dialog.findViewById(R.id.dialog_button);
// set the custom dialog components - text, image and button
dialog_Spinner = dialog.findViewById(R.id.dialog_spinner);
if(language.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_english_language).getConstantState()){
dialog_adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.Chinese_Dialog, android.R.layout.simple_spinner_item);
dialogButton.setText("完");
}else if(language.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_chinese_language).getConstantState()){
dialog_adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.English_Dialog, android.R.layout.simple_spinner_item);
}
dialog_adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
dialog_Spinner.setAdapter(dialog_adapter);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (dialog_Spinner.getSelectedItem().equals("Select Category")) {
Toast.makeText(MainActivity.this, "Select Category", Toast.LENGTH_SHORT).show();
return;
}else if(dialog_Spinner.getSelectedItem().equals("选择类别")){
Toast.makeText(MainActivity.this, "选择类别", Toast.LENGTH_SHORT).show();
return;
}
category = dialog_Spinner.getSelectedItem().toString();
customProgress.showProgress(MainActivity.this,"Uploading File...",false);
uploadFile(fileUri);
dialog.dismiss();
}
});
dialog.show();
break;
}
}
private void addToDB(String fileName, String fileDate, String fileURL) {
if(dialog_Spinner.getSelectedItem().toString().equals("Chinese Literature") || dialog_Spinner.getSelectedItem().toString().equals("中国文学")){
category = "Chinese Literature";
}else if(dialog_Spinner.getSelectedItem().toString().equals("Chinese linguistics") || dialog_Spinner.getSelectedItem().toString().equals("汉语语言学")){
category = "Chinese linguistics";
}else if(dialog_Spinner.getSelectedItem().toString().equals("Chinese culture") || dialog_Spinner.getSelectedItem().toString().equals("中华文化")){
category = "Chinese culture";
}else if(dialog_Spinner.getSelectedItem().toString().equals("Translation ch~Ar") || dialog_Spinner.getSelectedItem().toString().equals("阿汉汉阿翻译")){
category = "Translation ch~Ar";
}else if(dialog_Spinner.getSelectedItem().toString().equals("News room") || dialog_Spinner.getSelectedItem().toString().equals("头条")){
category = "News room";
}
id = databaseReference.child("Files").child(category).push().getKey();
if(extension.equals("docx")|| extension.equals("doc")|| extension.equals("txt")){
fileType = R.drawable.ic_word;
}else if(extension.equals("ppt")){
fileType = R.drawable.ic_powerpoint;
}else if(extension.equals("pdf")){
fileType = R.drawable.ic_pdf;
}else if(extension.equals("xls") || extension.equals("xlsx")){
fileType = R.drawable.ic_excel;
}else if(extension.equals("zip")){
fileType = R.drawable.ic_rar;
}else{
fileType = R.drawable.ic_insert_drive_file_black_24dp;
}
fileToDB = new FileModel(fileName,fileDate,id,fileURL,extension,category,fileType);
databaseReference.child("Files").child(category).child(id).setValue(fileToDB);
databaseReference.child("Files").child("AllFiles").child(id).setValue(fileToDB);
getFiles();
customProgress.hideProgress();
Toast.makeText(this, "Upload Successful", Toast.LENGTH_SHORT).show();
}
private void uploadFile(final Uri fileUri) {
UploadTask uploadTask;
storageReference = FirebaseStorage.getInstance().getReference().child("Files/").child(fileName);
uploadTask = storageReference.putFile(fileUri);
Task<Uri> task = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>()
{
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
{
return storageReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
@Override
public void onComplete(@NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
Uri file = task.getResult();
fileURL = file.toString();
addToDB(fileName,fileDate,fileURL);
} else
{
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
public void logout(View view) {
auth.signOut();
startActivity(new Intent(getApplicationContext(), StartActivity.class));
finish();
}
public void change_lng(View view) {
int selected_item = category_select.getSelectedItemPosition();
if(language.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_chinese_language).getConstantState()){
lng_status = "ch";
dataAdapter.notifyDataSetChanged();
adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.Chinese_Types, android.R.layout.simple_spinner_item);
language.setImageResource(R.drawable.ic_english_language);
} else if (language.getDrawable().getConstantState() == getResources().getDrawable(R.drawable.ic_english_language).getConstantState()) {
lng_status = "en";
dataAdapter.notifyDataSetChanged();
adapter = ArrayAdapter.createFromResource(getApplicationContext(),R.array.English_Types, android.R.layout.simple_spinner_item);
language.setImageResource(R.drawable.ic_chinese_language);
}
category_select.setAdapter(adapter);
category_select.setSelection(selected_item);
}
public void search(View view) {
final Dialog search_dialog = new Dialog(MainActivity.this);
search_dialog.setContentView(R.layout.search_dialog);
search_dialog.setTitle("Search");
// set the custom dialog components - text, image and button
final EditText search_field = search_dialog.findViewById(R.id.search_field);
Button search_btn = search_dialog.findViewById(R.id.search_button);
// if button is clicked, close the custom dialog
search_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
search_dialog.dismiss();
String searchName = search_field.getText().toString();
List<FileModel> searchResult = new ArrayList<>();
for(int i = 0; i < files.size(); i++){
String searchedName = files.get(i).getFile_name().replaceFirst("[.][^.]+$", "");
if(searchedName.equalsIgnoreCase(searchName) || searchedName.toLowerCase().contains(searchName.toLowerCase())){
searchResult.add(files.get(i));
}
}
DataAdapter newAdapter = new DataAdapter(searchResult);
recyclerView.setAdapter(newAdapter);
}
});
search_dialog.show();
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.DataVH>{
List<FileModel> fileModels;
public DataAdapter(List<FileModel> fileModels) {
this.fileModels = fileModels;
}
@NonNull
@Override
public DataVH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.data_item,null);
return new DataVH(view);
}
@Override
public void onBindViewHolder(@NonNull final DataVH holder, int position) {
final FileModel VhModel = fileModels.get(position);
holder.data_name.setText(VhModel.getFile_name());
holder.data_date.setText(VhModel.getFile_date());
holder.data_pic.setImageResource(VhModel.getDataType());
if(lng_status == null){
lng_status = "en";
}else if(lng_status.equals("en")){
holder.download_btn.setText("Download");
holder.delete_btn.setText("Delete");
} else if (lng_status.equals("ch")) {
holder.download_btn.setText("删除");
holder.delete_btn.setText("下载");
}
holder.download_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startDownload(getApplicationContext(),VhModel.getFile_name(),VhModel.getFileExtension(),Environment.DIRECTORY_DOWNLOADS,VhModel.getFileURL());
}
public void startDownload(Context context, String filename, String fileExtension,String destination,String url){
DownloadManager downloadManager = (DownloadManager) context.
getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context,destination,filename);
downloadManager.enqueue(request);
}
});
if(!user.getEmail().equals("<EMAIL>")){
holder.delete_btn.setVisibility(View.INVISIBLE);
holder.delete_btn.setEnabled(false);
}else{
holder.delete_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AlertDialog.Builder(MainActivity.this)
.setMessage("Are you Sure to delete this")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteID = dataAdapter.getTaskAt(holder.getAdapterPosition()).getId();
databaseReference.child("Files").child("AllFiles").child(deleteID).removeValue();
databaseReference.child("Files").child(VhModel.getCategory()).child(deleteID).removeValue();
StorageReference deletedfile = storage.getReferenceFromUrl(VhModel.getFileURL());
deletedfile.delete()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(MainActivity.this, "Delete Successful", Toast.LENGTH_SHORT).show();
getFiles();
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getFiles();
}
})
.show();
}
});
}
}
public FileModel getTaskAt(int position){
return fileModels.get(position);
}
@Override
public int getItemCount() {
return fileModels.size();
}
public class DataVH extends RecyclerView.ViewHolder{
ImageView data_pic;
TextView data_name,data_date;
Button download_btn,delete_btn;
public DataVH(@NonNull View itemView) {
super(itemView);
data_name = itemView.findViewById(R.id.file_name);
data_date = itemView.findViewById(R.id.file_date);
data_pic = itemView.findViewById(R.id.dataType);
download_btn = itemView.findViewById(R.id.download_btn);
delete_btn = itemView.findViewById(R.id.delete_btn);
}
}
}
public static boolean checkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr != null) {
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
// connected to the mobile provider's data plan
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
return false;
}
}
| b7978bcb383064afcfbafcd7de8619df054436c4 | [
"Java",
"Gradle"
] | 2 | Gradle | MedoWaleed07/SilkRoad_culture_platform | f1a27f59145cd363e5f063d46330c925ae615868 | 4f08b71ad905ca146f882462522c747e2517165e | |
refs/heads/master | <repo_name>VinceOC34/test-P3<file_sep>/P3_v2/src/Mastermind.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Mastermind extends LibrairyAbstract {
public Mastermind() {
// choix du Mode----------------------------------------------------------------------------------------------------------------------------------------
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Menu Mastermind - Quel mode voulez vous utiliser ?");
System.out.println();
System.out.println("1. Challenger (trouver la combinaison secrète de l'ordinateur)");
System.out.println("2. Défenseur (l'ordinateur essaye de trouver votre combinaison secrète)");
System.out.println("3. Duel (tour à tour contre l'ordinateur)");
System.out.println("4. Retourner au menu général pour changer de Jeu");
selectMode = sc.nextInt();
}catch (InputMismatchException e){
System.out.println("La saisie ne semble pas bonne, merci de recommencer :");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
if (selectMode ==1) {
Object one = new Challenger_mastermind();
}
else if (selectMode ==4) {
Object men = new Menu();
}
}
}
<file_sep>/P3_v2/src/Duel_plusOuMoins.java
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Duel_plusOuMoins extends LibrairyAbstract{
public Duel_plusOuMoins() {
Object test = new nbEssai(0);
System.out.println(nbEssai);
}
public void nbFigures() {
int securityLoop = 0;
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Combien de chiffres voulez vous utiliser ?");
nbChiffre = sc.nextInt();
this.nbChiffre=nbChiffre;
}catch (InputMismatchException e){
System.out.println("Je ne comprend pas votre réponse désolé, essayez encore");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
}
public void userInput() {
int securityLoop = 0;
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Choisissez votre combinaison à "+nbChiffre);
userInput = sc.nextInt();
this.userInput=userInput;
}catch (InputMismatchException e){
System.out.println("Je ne comprend pas votre réponse désolé, essayez encore");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
}
// jeu d'intro-- aléa pour déterminer qui commence :)
// System.out.println("Déterminons, qui va commencer :");
// System.out.println("Un chiffre de 1 à 10 vient d'être caché");
// System.out.println("Le plus proche entre l'ordinateur et vous commence");
// Random rand = new Random();
// int whoStart = rand.nextInt(11);
//
// System.out.println("Entrez votre chiffre :");
// Scanner sc = new Scanner(System.in);
// int userAttack = sc.nextInt();
// rand = new Random();
// int computeAttack = rand.nextInt(11);
// System.out.println("Le chiffre caché est "+whoStart+" Vous avez proposé "+userAttack+" L'ordinateur a proposé "+computeAttack);
// System.out.println(userAttack - whoStart);
// System.out.println(computeAttack - whoStart);
// //if (userAttack - whoStart)
// // à finir
}
<file_sep>/P3_v2/src/MainP3V2.java
import java.util.Scanner;
import java.util.InputMismatchException;
public class MainP3V2 extends LibrairyAbstract{
public static void main(String[] args) {
// TODO Auto-generated method stub
Object men = new Menu();
// test.nbAttempt();
//
// test.nbFigures();
//
// test.userInput();
}
}
<file_sep>/P3_v2/src/nbEssai.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class nbEssai extends LibrairyAbstract{
public nbEssai(int nbEssai) {
securityLoop = 0;
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Combien de tentatives avant de perdre le jeux ?");
nbEssai = sc.nextInt();
this.nbEssai=nbEssai;
}catch (InputMismatchException e){
System.out.println("La saisie ne semble pas bonne, merci de recommencer :");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
}
}
<file_sep>/P3_v2/try/README.md
# try
Test for OC
<file_sep>/P3_v2/src/Defenseur_plusOuMoins.java
import java.util.Random;
public class Defenseur_plusOuMoins extends LibrairyAbstract {
}
<file_sep>/P3_v2/src/ClassEnum.java
import java.util.Random;
import java.util.Scanner;
import java.util.InputMismatchException;
public enum ClassEnum {
comuptAttack(),
userAttack(),
nbAttempt(),
Menu();
int nbEssais;
int nbChiffres;
int userInput;
int selectGame;
int selectMode;
public ClassEnum() {
int securityLoop = 0;
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Combien de tentatives avant de perdre le jeux ?");
nbEssais = sc.nextInt();
this.nbEssais=nbEssais;
}catch (InputMismatchException e){
System.out.println("La saisie ne semble pas bonne, merci de recommencer :");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
}
public void nbFigures() {
int securityLoop = 0;
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Combien de chiffres voulez vous utiliser ?");
nbChiffres = sc.nextInt();
this.nbChiffres=nbChiffres;
}catch (InputMismatchException e){
System.out.println("Je ne comprend pas votre réponse désolé, essayez encore");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
}
public void userInput() {
int securityLoop = 0;
do{ // boucle en cas d'erreur de saisie
try {
securityLoop =0;
Scanner sc = new Scanner (System.in);
System.out.println("Choisissez votre combinaison à "+nbChiffres);
userInput = sc.nextInt();
this.userInput=userInput;
}catch (InputMismatchException e){
System.out.println("Je ne comprend pas votre réponse désolé, essayez encore");
securityLoop++;}
}while (securityLoop ==1);// fin de la boucle
}
}
| 2b7220846e11b8b4ee6b8b8b0b9ece961934bd9f | [
"Markdown",
"Java"
] | 7 | Java | VinceOC34/test-P3 | 750720f740613006a5a6b7dd928cbbae8caaae6a | 4523216e1f3a9874752f39bf34147713cadea16e | |
refs/heads/master | <repo_name>amanda/lyrics_scraper<file_sep>/az_scraper.py
#!usr/bin/env python
# -*- coding: utf-8 -*-
'''a shitty little a-z lyrics scraper for texty fun.
returns a json file of all the lyrics by a given artist by song.
azlyrics doesn't like scraping (eep) so use with caution!'''
from pattern.web import URL, DOM, abs, plaintext
import re, argparse, json
BASE_URL = 'http://www.azlyrics.com/'
def all_lyrics(artist):
clean = re.sub(r"\s+|'", '', artist)
url = URL(BASE_URL + artist[0] + '/' + clean + '.html')
dom = DOM(url.download())
titles = [a.content for a in dom('div#listAlbum a')]
ew_amazon = [abs(link.attributes.get('href', ''), base=url.redirect or
url.string) for link in dom('div#listAlbum a')]
songlinks = [l for l in ew_amazon if 'amazon' not in l]
lyrics = []
for link in songlinks:
song_url = URL(link)
song_dom = DOM(song_url.download())
lyrics.append(plaintext(song_dom('div#main div')[4:5][0].content))
zippy_lyrics = zip(titles, lyrics)
return json.dumps(zippy_lyrics, sort_keys=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('artist', type=str, help='artist to get lyrics from.')
args = parser.parse_args()
fname = args.artist + '-lyrics.json'
with open(fname, 'w') as f:
f.write(all_lyrics(args.artist))
<file_sep>/requirements.txt
Pattern==2.6
argparse==1.3.0
wsgiref==0.1.2
<file_sep>/README.md
# lyrics_scraper
a simple lyrics scraper made to play with the [pattern-web module](http://www.clips.ua.ac.be/pages/pattern-web).
## usage:
```
pip install -r requirements.txt
python az_scraper.py 'artistname'
```
returns a json file of lyrics by the specified artist.
## todo:
- learn that i need to stop trying to scrape websites without APIs, they don't have APIs for a reason you're just going to get your ip banned :'(
| 65f525727a079cde11211bffc4de69fe5922a748 | [
"Markdown",
"Python",
"Text"
] | 3 | Python | amanda/lyrics_scraper | 66d171f7a990a4cd9c0928150ff8cc8caf8ad6e5 | bcd9b4a3c36754d6d5f82e353f658eb7827b7557 | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnviromentMovementLoop : MonoBehaviour
{
public Vector3 startPos;
public Vector3 targetPos;
private Vector3 moveTo;
public float movementSpeed = 4;
// Start is called before the first frame update
void Start()
{
if(startPos == new Vector3(0, 0, 0))
{
startPos = this.transform.position;
}
moveTo = targetPos;
StartCoroutine("MoveObject");
}
private void Update()
{
this.transform.position = Vector3.LerpUnclamped(transform.position, moveTo, movementSpeed * Time.deltaTime);
}
IEnumerator MoveObject()
{
MoveTo();
yield return new WaitForSeconds(1);
MoveFrom();
yield return new WaitForSeconds(1);
StartCoroutine("MoveObject");
}
private void MoveTo()
{
moveTo = targetPos;
}
private void MoveFrom()
{
moveTo = startPos;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Restart : MonoBehaviour
{
public Transform startPos;
private CharacterController cc;
private void Start()
{
cc = this.GetComponent<CharacterController>();
}
void Update()
{
if (Input.GetKeyDown("r"))
RestartPlayer();
}
void RestartPlayer()
{
cc.enabled = false;
gameObject.transform.position = startPos.position;
gameObject.transform.rotation = startPos.rotation;
Debug.Log(new Vector3(startPos.position.x, startPos.position.y, startPos.position.z));
cc.enabled = true;
Timer.singleton.RestartTimer();
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Danger")
RestartPlayer();
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FinishTrigger : MonoBehaviour
{
// Start is called before the first frame update
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
Timer.singleton.TimerFinished();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
public static Timer singleton;
public float currTime = 0.0f;
public float bestTime = 0.0f;
public Text currTimeText;
public Text timeToBeatText;
public bool timerActive = false;
private void Awake()
{
if (!(singleton is null) && singleton != this)
Destroy(this);
singleton = this;
}
void Update()
{
if(timerActive)
RunTimer();
}
public void RunTimer()
{
currTime += Time.deltaTime;
FormatTimer(currTime, currTimeText, "");
if(currTime > bestTime && bestTime != 0)
{
currTimeText.color = new Color(1, 0, 0);
}
}
private void FormatTimer(float t, Text displayText, string info)
{
string minutes = Mathf.Floor(t / 60).ToString("00");
string seconds = Mathf.Floor(t % 60).ToString("00");
string milis = Mathf.Floor((t * 10) % 10).ToString("0");
displayText.text = info + string.Format("{0}:{1}.{2}", minutes, seconds, milis);
}
public void TimerFinished()
{
if (!timerActive)
return;
timerActive = false;
if(currTime < bestTime || bestTime == 0)
{
bestTime = currTime;
FormatTimer(bestTime, timeToBeatText, "Time To Beat: ");
}
}
public void StartTimer()
{
timerActive = true;
}
public void RestartTimer()
{
currTime = 0;
timerActive = false;
FormatTimer(currTime, currTimeText, "");
currTimeText.color = new Color(0, 1, 0);
}
}
<file_sep>
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
public class MenuButton : MonoBehaviour, IPointerClickHandler
{
public string _action;
public void OnPointerClick(PointerEventData eventData)
{
MenuEvent(_action);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
MenuEvent(_action);
}
}
private void MenuEvent(string a)
{
if(a == "play")
{
SceneManager.LoadScene("Level1");
}
if(a == "exit")
{
Application.Quit();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ladder : MonoBehaviour
{
public GameObject playerOBJ;
public bool canClimb = false;
float speed = 5;
void OnCollisionEnter(Collision coll)
{
if (coll.gameObject.tag == "Player")
{
canClimb = true;
playerOBJ = coll.gameObject;
playerOBJ.GetComponent<CharacterController>().enabled = false;
}
}
void OnCollisionExit(Collision coll2)
{
if (coll2.gameObject.tag == "Player")
{
canClimb = false;
playerOBJ.GetComponent<CharacterController>().enabled = true;
playerOBJ = null;
}
}
void Update()
{
if (canClimb)
{
if (Input.GetKey(KeyCode.W))
{
// Debug.Log("AAAAH");
playerOBJ.transform.Translate(new Vector3(0, 1, 0) * Time.deltaTime * speed);
}
if (Input.GetKey(KeyCode.S))
{
playerOBJ.transform.Translate(new Vector3(0, -1, 0) * Time.deltaTime * speed);
if (playerOBJ.GetComponent<PlayerMovement>().isGrounded)
{
canClimb = false;
playerOBJ.GetComponent<CharacterController>().enabled = true;
}
}
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
private Camera mainCam;
public float speed = 6f;
public float gravityNorm = -9.81f;
public float gravity;
public float jumpH = 2;
public float lockedZ;
public float lockedX;
public float z;
public float x;
public Transform groundCheck;
public Transform wallCheckLeft;
public Transform wallCheckRight;
public float groundDistance = 0.4f;
public float wallDistance = 0.3f;
public bool isGrounded;
public bool isWallLeft;
public bool isWallRight;
public bool isSliding = false;
public bool canMove = true;
public Vector3 velocity;
public Vector3 movement;
public LayerMask groundChecks;
private void Awake()
{
mainCam = Camera.main;
}
void Update()
{
if (canMove)
{
WallRun();
if (Input.GetKey(KeyCode.LeftShift) && !Input.GetKey("c"))
{
speed = 11f;
}
else
{
speed = 6f;
}
}
if (isSliding)
{
StartCoroutine("Slide");
}
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundChecks);
if (isGrounded && velocity.y < 0)
{
velocity.y = -1f;
}
x = Input.GetAxis("Horizontal");
z = Input.GetAxis("Vertical");
if (canMove)
{
movement = transform.right * x + transform.forward * z;
}
else if (!canMove)
{
movement = transform.right * lockedX + transform.forward * lockedZ;
}
controller.Move(movement * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
if(Input.GetKeyDown("space") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpH * -2f * gravity);
}
if (Input.GetKeyDown("c") && !isSliding)
{
transform.localScale = new Vector3(1,0.5f,1);
if (z > 0.5f && Input.GetKey(KeyCode.LeftShift))
{
isSliding = true;
}
}
else if(Input.GetKeyUp("c") )
{
transform.localScale = new Vector3(1, 1, 1);
isSliding = false;
canMove = true;
}
}
private void WallRun()
{
isWallLeft = Physics.CheckSphere(wallCheckLeft.position, wallDistance, groundChecks);
isWallRight = Physics.CheckSphere(wallCheckRight.position, wallDistance, groundChecks);
if ((isWallLeft || isWallRight) && velocity.y < 0)
{
gravity = -5f;
}
else
{
gravity = gravityNorm;
}
}
IEnumerator Slide()
{
isSliding = false;
LockMovement();
speed = 15f;
yield return new WaitForSeconds(0.4f);
canMove = true;
isSliding = false;
canMove = true;
}
void LockMovement()
{
lockedZ = z;
lockedX = x;
canMove = false;
}
} | ff18468038266c0e8c49bf051b7e81f8de39910d | [
"C#"
] | 7 | C# | JelmerDeV/BPW1 | 057a769c700eec395811c65294a9c303e3447a30 | 2e25f8f5a554d44f9e79aa663be6efbb5f02f0c1 | |
refs/heads/master | <repo_name>mutongliwansui/JavaLearning01<file_sep>/src/main/java/com/mutongli/concurrent/item/OrderDelayItem.java
package com.mutongli.concurrent.item;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
public class OrderDelayItem implements Delayed {
private static final Logger LOGGER = Logger.getLogger(OrderDelayItem.class);
private String ordercode; //订单编码
private long exptime; //过期时间(豪秒)
private long createtime; //创建时间(毫秒)
private static final TimeUnit DEFAULT_TIMEUNIT = TimeUnit.MILLISECONDS;
public static final String DEFAULT_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private OrderDelayItem() {
}
/**
* 创建订单项,并赋予创建时间和过期时间
* @param ordercode 订单号
* @param exptime 过期时间
* @param unit 过期时间单位
* @param date 创建时间
* @return
*/
public static OrderDelayItem newInstance(String ordercode, long exptime, TimeUnit unit, Date date){
OrderDelayItem item = new OrderDelayItem();
item.setOrdercode(ordercode);
item.setCreatetime(date.getTime());
item.setExptime(DEFAULT_TIMEUNIT.convert(exptime,unit) + item.createtime);
return item;
}
/**
* 创建订单项,并赋予创建时间和过期时间
* @param ordercode 订单号
* @param exptime 过期时间
* @param unit 过期时间单位
* @param createtime 创建时间
* @param pattern 创建时间格式(默认yyyy-mm-dd hh:mi:ss)
* @return
*/
public static OrderDelayItem newInstance(String ordercode, long exptime, TimeUnit unit, String createtime, String pattern){
OrderDelayItem item = null;
try {
DateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse(createtime);
item = newInstance(ordercode,exptime,unit,date);
} catch (ParseException e) {
LOGGER.error("parse createtime failed",e);
}finally {
return item;
}
}
/**
* 创建订单项,并赋予创建时间和过期时间
* @param ordercode 订单号
* @param exptime 过期时间
* @param unit 过期时间单位
* @param createtime 创建时间(默认格式yyyy-mm-dd)
* @return
*/
public static OrderDelayItem newInstance(String ordercode, long exptime, TimeUnit unit, String createtime){
return newInstance(ordercode,exptime,unit,createtime,DEFAULT_TIME_PATTERN);
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(this.exptime - System.currentTimeMillis(),DEFAULT_TIMEUNIT);
}
@Override
public int compareTo(Delayed o) {
return Long.valueOf(this.exptime).compareTo(Long.valueOf(((OrderDelayItem)o).getExptime()));
}
public String getOrdercode() {
return ordercode;
}
public void setOrdercode(String ordercode) {
this.ordercode = ordercode;
}
public long getExptime() {
return exptime;
}
public void setExptime(long exptime) {
this.exptime = exptime;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
}
<file_sep>/src/main/java/com/mutongli/hash/LrnHashMap.java
package com.mutongli.hash;
import java.util.HashMap;
import java.util.Map;
/**
* @author mtl
* @Description: HashMap学习
* @date 2019/7/30 17:26
*/
public class LrnHashMap {
public void testPutReturn(){
HashMap hb = new HashMap();
Object rt1 = hb.put("123","345"); //HashMap的put方法返回的是之前的值,此时hb是第一次存入key="123",所以之前的值为空
System.out.println(rt1);
Object rt2 = hb.put("123","456"); //此时是第二次存入key="123",所以之前的值是345
System.out.println(rt2);
}
public static void main(String[] args) {
new LrnHashMap().testPutReturn();
}
}
<file_sep>/src/main/java/com/mutongli/innerclass/AnonymousInnerDemo.java
package com.mutongli.innerclass;
/**
* @author mtl
* @Description: 匿名内部类
* @date 2019/7/29 21:50
*/
public class AnonymousInnerDemo {
public void setInf(Interface inf){
inf.method();
}
public void test(final int a,int b){
// b = 5; //如果对b没有改变值,则匿名内部类可以访问该变量,等同于被final修饰,如果改变了b的值,则匿名内部类访问该变量会编译报错
int c = 0;
// c = 3; //与变量b相同
this.setInf(new Interface() {
@Override
public void method() {
System.out.println("param1:"+a);
System.out.println("param2:"+b); //匿名内部类只能访问外部的常量(被final修饰,或者在外部除了定义时赋值,后续没有再改变值的)
System.out.println("param3:"+c);
System.out.println("test => setInf => method");
}
});
}
public static void main(String[] args) {
new AnonymousInnerDemo().test(1,2);
}
}
interface Interface{
void method();
}
<file_sep>/src/main/java/com/mutongli/inf/TestBed.java
package com.mutongli.inf;
public interface TestBed {
public void fun();
class TestInner{
}
}
<file_sep>/src/main/java/com/mutongli/innerclass/StaticInnerDemo.java
package com.mutongli.innerclass;
/**
* @author mtl
* @Description: 静态内部类
* @date 2019/7/29 21:25
*/
public class StaticInnerDemo {
private String name;
private static String password = "123";
private static void printPassword(){
System.out.println("outter:" + password);
}
private void printName(){
System.out.println("outter:"+name);
}
static class Inner{
public void test(){
// System.out.println(StaticInnerDemo.this.name); //静态内部类无法访问外部类的非静态成员变量或者方法
System.out.println(password); //可以访问外部类的静态变量和静态方法
// StaticInnerDemo.this.printName();
printPassword();
}
private static String password = "<PASSWORD>"; //静态内部类可以定义静态变量
//静态内部类可以定义静态方法
public static void testStatic(){
System.out.println(password);
System.out.println(StaticInnerDemo.password);
}
}
public static void main(String[] args) {
new StaticInnerDemo.Inner().test(); //静态内部类创建不需要依赖外部类对象,直接new 外部类名.内部类名()就可以创建了
}
}
<file_sep>/src/main/java/com/mutongli/TestNioSocket.java
package com.mutongli;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
public class TestNioSocket {
public static void main(String[] args) {
try {
//创建ServerSocketChannel,监听8080端口
ServerSocketChannel socketChannel = ServerSocketChannel.open();
InetSocketAddress socketAddress = new InetSocketAddress(8080);
socketChannel.socket().bind(socketAddress);
//设置为非阻塞模式
socketChannel.configureBlocking(false);
//为socketChannel注册选择器
Selector selector = Selector.open();
socketChannel.register(selector, SelectionKey.OP_ACCEPT);
//创建处理器
while (true){
//等待请求,每次等待阻塞3s,超过3s后线程继续向下运行,如果传入0或者不传参数将一直阻塞
if(selector.select(3000) == 0){
continue;
}
//获取待处理的SelectionKey
Iterator<SelectionKey> keyiter = selector.selectedKeys().iterator();
while (keyiter.hasNext()){
SelectionKey key = keyiter.next();
//启动新线程处理SelectionKey
HttpHandler handler = new HttpHandler(key);
//处理完后,从待处理的SelectionKey迭代器中移除当前使用的key
new Thread(handler).run();
keyiter.remove();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static class HttpHandler implements Runnable{
private int bufferSize = 1024;
private String localCharset = "UTF-8";
private SelectionKey key;
public HttpHandler(SelectionKey key) {
this.key = key;
}
public void handleAccept() throws IOException{
SocketChannel cilentChannel = ((ServerSocketChannel)key.channel()).accept();
cilentChannel.configureBlocking(false);
cilentChannel.register(key.selector(),SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
}
public void handleRead() throws IOException{
//获取channel
SocketChannel sc = (SocketChannel) key.channel();
//获取buffer并重置
ByteBuffer buffer = (ByteBuffer) key.attachment();
buffer.clear();
//没有读取到内容则关闭
if(sc.read(buffer) == -1){
sc.close();
}else{
//接收请求数据
buffer.flip();
String receivedStr = Charset.forName(localCharset).newDecoder().decode(buffer).toString();
//控制台打印请求报文头
String [] requestMessage = receivedStr.split("\r\n");
for (String s :
requestMessage) {
System.out.println(s);
//遇到空行说明报文头已经打印完
if(s.isEmpty()){
break;
}
}
//控制台打印首行信息
String [] firstLine = requestMessage[0].split(" ");
System.out.println();
System.out.println("Method:\t"+firstLine[0]);
System.out.println("url:\t"+firstLine[1]);
System.out.println("HTTP Version:\t"+firstLine[2]);
System.out.println();
//返回客户端
StringBuilder sendStr = new StringBuilder();
sendStr.append("HTTP/1.1 200 OK\r\n");
sendStr.append("Content-Type:text/html;charset="+localCharset+"\r\n");
sendStr.append("\r\n");
sendStr.append("<html><head><title>显示报文</title></head><body>");
sendStr.append("接收到请求报文是:</br>");
for (String s :
requestMessage) {
sendStr.append(s + "<br/>");
}
sendStr.append("</body></html>");
buffer = ByteBuffer.wrap(sendStr.toString().getBytes(localCharset));
sc.write(buffer);
sc.close();
}
}
@Override
public void run() {
try {
//接收到连接请求时
if(key.isAcceptable()){
handleAccept();
}
//读数据
if(key.isReadable()){
handleRead();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/src/main/resources/log4j.properties
log4j.rootCategory=INFO, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[JavaLearning01] %d %p %t %c - %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=${catalina.home}/JavaLearning01/logs/log.txt
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.DatePattern ='.'yyyy-MM-dd
log4j.appender.R.layout.ConversionPattern=[JavaLearning01] %d- %p %t %c - %m%n
log4j.logger.com.halo=INFO
log4j.logger.org.hibernate=ERROR
log4j.logger.org.opensymphony=ERROR
log4j.logger.org.springframework=ERROR | c1def65877cc02e13bdafa2da8f9b2cc1bd119d6 | [
"Java",
"INI"
] | 7 | Java | mutongliwansui/JavaLearning01 | 595ea317894ea4618838917bdbf70277033403fd | 06d367b0b77526f557dd0d97dabd10cad6233c50 | |
refs/heads/master | <repo_name>gustavoalvesdev/desafios-uri-online<file_sep>/Desafio1011.py
raio_esfera = float(input())
volume = (4.0 / 3) * 3.14159 * raio_esfera ** 3
print('VOLUME = %.3f' % volume)
<file_sep>/Desafio1013.py
valores = input()
separaValores = valores.split()
a = int(separaValores[0])
b = int(separaValores[1])
c = int(separaValores[2])
maiorAB = (a + b + abs(a - b)) / 2
maiorABC = (maiorAB + c + abs(maiorAB - c)) / 2
print('%i eh o maior' % maiorABC)
<file_sep>/README.md
# desafios-uri-online
Desafios do Site UriOnlineJudge
<file_sep>/Desafio1015.py
p1 = input()
p2 = input()
separaP1 = p1.split()
separaP2 = p2.split()
x1 = float(separaP1[0])
y1 = float(separaP1[1])
x2 = float(separaP2[0])
y2 = float(separaP2[1])
distancia = (((x2 - x1) ** 2) + ((y2 - y1) ** 2)) ** 0.5
print('%.4f' % distancia)
<file_sep>/Desafio1004.java
/*
* Leia dois valores inteiros. A seguir, calcule o produto entre estes
dois valores e atribua esta operação à variável PROD.
A seguir mostre a variável PROD com mensagem correspondente.
*/
package exercicios;
import java.util.Scanner;
/**
*
* @author <NAME>
*/
public class Desafio1004 {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
int valor1;
int valor2;
int prod;
valor1 = entrada.nextInt();
valor2 = entrada.nextInt();
prod = valor1 * valor2;
System.out.println("PROD = " + prod);
}
}
<file_sep>/Desafio1009.py
nome_vend = input()
sal_fixo = float(input())
vendas = float(input())
sal_total = sal_fixo + vendas * 0.15
print('TOTAL = R$ %.2f' % sal_total)
<file_sep>/Desafio1094.py
casos_teste = int(input())
cobaias_experimento = []
total_cobaias = 0
total_coelhos = 0
total_ratos = 0
total_sapos = 0
percent_coelhos = 0
percent_ratos = 0
percent_sapos = 0
for i in range(0, casos_teste):
cobaias_experimento.append(input().split())
for i in range(len(cobaias_experimento)):
total_cobaias = total_cobaias + int(cobaias_experimento[i][0])
if cobaias_experimento[i][1] == 'C':
total_coelhos = total_coelhos + int(cobaias_experimento[i][0])
elif cobaias_experimento[i][1] == 'R':
total_ratos = total_ratos + int(cobaias_experimento[i][0])
elif cobaias_experimento[i][1] == 'S':
total_sapos = total_sapos + int(cobaias_experimento[i][0])
percent_coelhos = (total_coelhos * 100) / total_cobaias
percent_ratos = (total_ratos * 100) / total_cobaias
percent_sapos = (total_sapos * 100) / total_cobaias
print('Total: {0} cobaias'.format(total_cobaias))
print('Total de coelhos: {0}'.format(total_coelhos))
print('Total de ratos: {0}'.format(total_ratos))
print('Total de sapos: {0}'.format(total_sapos))
print('Percentual de coelhos: {0:.2f} %'.format(percent_coelhos))
print('Percentual de ratos: {0:.2f} %'.format(percent_ratos))
print('Percentual de sapos: {0:.2f} %'.format(percent_sapos))<file_sep>/Desafio1001.java
/*
* Leia 2 valores inteiros e armazene-os nas variáveis A e B. Efetue a soma de A
e B atribuindo o seu resultado na variável X. Imprima X conforme exemplo
apresentado abaixo. Não apresente mensagem alguma além daquilo que está sendo
especificado e não esqueça de imprimir o fim de linha após o resultado, caso
contrário, você receberá "Presentation Error".
*/
package exercicios;
import java.util.Scanner;
/**
*
* @author <NAME>
*/
public class Desafio1001 {
public static void main(String[] args) {
int A;
int B;
Scanner entrada = new Scanner(System.in);
A = entrada.nextInt();
B = entrada.nextInt();
int X = A + B;
System.out.println("X = " + X);
}
}
<file_sep>/Desafio1014.py
X = int(input())
Y = round((float(input())), 1)
totalGasto = X / Y
print('%.3f km/l' % totalGasto)
<file_sep>/Desafio1010.py
peca1 = input()
peca2 = input()
peca1_partes = peca1.split()
peca2_partes = peca2.split()
cod_peca1 = int(peca1_partes[0])
numero_peca1 = int(peca1_partes[1])
val_unit_peca1 = float(peca1_partes[2])
cod_peca2 = int(peca2_partes[0])
numero_peca2 = int(peca2_partes[1])
val_unit_peca2 = float(peca2_partes[2])
val_total = numero_peca1 * val_unit_peca1 + numero_peca2 * val_unit_peca2
print('VALOR A PAGAR: R$ %.2f' % val_total)
<file_sep>/Desafio1012.py
valores = input()
separa_valores = valores.split()
a = float(separa_valores[0])
b = float(separa_valores[1])
c = float(separa_valores[2])
triangulo = (a * c) / 2
circulo = 3.14159 * c ** 2
trapezio = ((a + b) * c) / 2
quadrado = b * b
retangulo = a * b
print('TRIANGULO: %.3f' % triangulo)
print('CIRCULO: %.3f' % circulo)
print('TRAPEZIO: %.3f' % trapezio)
print('QUADRADO: %.3f' % quadrado)
print('RETANGULO: %.3f' % retangulo)
<file_sep>/Desafio1008.py
num_func = int(input())
horas_trab = int(input())
valor_hora = float(input())
sal_func = horas_trab * valor_hora
print('NUMBER = %i' % num_func)
print('SALARY = %i' % sal_func)
<file_sep>/Desafio1002.py
# A fórmula para calcular a área de uma circunferência é: area = π . raio2. Considerando para este
# problema que π = 3.14159:
# - Efetue o cálculo da área, elevando o valor de raio ao quadrado e multiplicando por π.
raio = float(input())
area = 3.14159 * (raio * raio)
print('A={:.4f}'.format(area))
<file_sep>/Desafio1095.py
i = 1
j = 60
for c in range(0, 13):
print('I={} J={}'.format(i, j))
i = i + 3
j = j - 5
<file_sep>/Desafio1001.py
# Leia 2 valores inteiros e armazene-os nas variáveis A e B. Efetue a soma de A e B atribuindo o seu resultado na
# variável X. Imprima X conforme exemplo apresentado abaixo. Não apresente mensagem alguma além daquilo que está sendo
# especificado e não esqueça de imprimir o fim de linha após o resultado, caso contrário, você
# receberá "Presentation Error".
a = int(input())
b = int(input())
soma = a + b
print('X = {}'.format(soma))
<file_sep>/Desafio1096.py
i = 1
for c in range(0,5):
j = 7
for d in range(0,3):
print('I={} J={}'.format(i, j))
j = j - 1
i = i + 2<file_sep>/Desafio1002.java
/*
* A fórmula para calcular a área de uma circunferência é: area = π . raio2.
Considerando para este problema que π = 3.14159:
- Efetue o cálculo da área, elevando o valor de raio ao
quadrado e multiplicando por π.
*/
package exercicios;
import java.util.Scanner;
/**
*
* @author <NAME>
*/
public class Desafio1002 {
public static void main(String[] args) {
double raio;
double n = 3.14159;
double area;
Scanner entrada = new Scanner(System.in);
raio = entrada.nextDouble();
area = n * Math.pow(raio, 2);
System.out.printf("A=%.4f\n", area);
}
}
| b7948c80cd6bdf8e48932e0768316a607536e12b | [
"Markdown",
"Java",
"Python"
] | 17 | Python | gustavoalvesdev/desafios-uri-online | e50ad0fbe192fdf14e6d74bff329bb458938f409 | 462b9000756b34e391801ebc485d37ef908fcda4 | |
refs/heads/master | <file_sep>FROM grafana/grafana:4.4.2
RUN apt-get update && apt-get install -y curl gettext-base telnet supervisor nginx openssl && rm -rf /var/lib/apt/lists/*
WORKDIR /etc/grafana
COPY datasources ./datasources
WORKDIR /etc/grafana
COPY grafana.ini ./grafana.ini
WORKDIR /etc/grafana
RUN openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/cert.key -out /etc/nginx/cert.crt -subj "/C=IN/ST=Karnataka/L=Bangalore/O=Grafana/OU=IT Department/CN=localhost"
RUN mkdir -p mkdir /opt/template/logs
ADD https://releases.hashicorp.com/consul-template/0.19.5/consul-template_0.19.5_linux_amd64.tgz /tmp/consul-template.tgz
RUN cd /tmp && tar xvfz /tmp/consul-template.tgz && mv consul-template /bin/consul-template
WORKDIR /etc/nginx/sites-enabled
COPY default ./default
WORKDIR /etc/grafana
COPY grafana.ini.ctmpl ./grafana.ini.ctmpl
WORKDIR /etc/grafana
COPY config.hcl ./config.hcl
COPY start.sh ./start.sh
RUN chmod u+x start.sh
RUN mkdir -p /etc/supervisor/conf.d/
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
WORKDIR /app
COPY entrypoint.sh ./
RUN chmod u+x entrypoint.sh
WORKDIR /app
COPY dashboard.json ./
COPY add_dashboard.sh ./
RUN chmod u+x add_dashboard.sh
ENTRYPOINT ["/usr/bin/supervisord"]
<file_sep>version: '3.2'
services:
myvault:
image: vault
container_name: myvault
ports:
- "127.0.0.1:8200:8200"
env_file: configuration.env
volumes:
- ./vault/file:/vault/file:rw
- ./vault/config:/vault/config:rw
cap_add:
- IPC_LOCK
entrypoint: vault server -config=/vault/config/vault.json
influxdb:
build: influxdb
env_file: configuration.env
ports:
- '8086:8086'
volumes:
- influxdb_data:/var/lib/influxdb
consul:
image: "consul"
hostname: "consul"
command: agent -server -bind 0.0.0.0 -client 0.0.0.0 -bootstrap-expect=1
ports:
- "8400:8400"
- "8500:8500"
- "8600:53/udp"
volumes:
- ./consul/config:/consul/config
grafana:
build: grafana
env_file: configuration.env
links:
- influxdb
ports:
- '3000:3000'
- '80:80'
- '443:443'
volumes:
- grafana_data:/var/lib/grafana
git2consul:
image: cimpress/git2consul
depends_on:
- consul
container_name: git2consul
volumes:
- ./config/git2consul:/config
command: --endpoint consul --config-file /config/git2consul.json
volumes:
grafana_data: {}
influxdb_data: {}
<file_sep>
Docker – Grafana – InfluxDB – Consul-Template – Consul – Git2Consul – Vault
The above application are experimented in Mac Docker engine
Docker Code Repo: https://github.com/vimalkrish/GICV-Version-2
Git2consul Repo: https://github.com/vimalkrish/git2consul_data
*Enabled Https for Grafana
*disabled grafana Signup
*Created dashboard via JSON file
*Manage Grafana Configuration in Consul using Consul-template
*Manage Consul Key/Value in git2consul
*store the secret keys in Vault
Grafana login stored in Vault
Grafana Login:
https://127.0.0.1
user: admin
password: <PASSWORD>
-----------------
InfluxDB database
Database: influx
User: admin
Password: <PASSWORD>
------------------
To start the docker containers
Clone the git repository
#git clone <EMAIL>:vimalkrish/GICV-Version-2.git
#cd GICV-Version-2/grafana
#docker compose up -d
Now you can see 5 container running
1 – Consul
2 – Grafana, consul-template
3 – Vault
4 – influxdb
5 – git2consul
Check all the services are started
#docker ps
Applications:
Grafana: https://127.0.0.1
InfluxDB Server: 127.0.0.1 Port: 8086
Consul Server: http://127.0.0.1:8500
Vault Server: 127.0.0.1 port: 8200
Vault key and Token
Unseal Key 1: <KEY>
Unseal Key 2: <KEY>
Unseal Key 3: <KEY>
Unseal Key 4: <KEY>
Unseal Key 5: <KEY>
Initial Root Token: <PASSWORD>
Login to vault container and initialize it
#vault init
Unseal Vault using 3 keys
#vault operator unseal
#vault operator unseal
#vault operator unseal
Init the root token
#vault login
From the host environment (i.e. outside of the docker image):
#alias vault='docker exec -it CONTAINER-ID vault "$@"'
#vault read secret/grafana
--------------------------------------------------------------------
Telegraf
Install telegraf in local laptop and send the metrics to InfluxDB
Command to Install in MAC
brew install telegraf
update the configuration file /usr/local/etc/telegraf.conf
add the url “http://localhost:8086” and Read metrics, cpu, memory and disk
once the influxdb container is up, start the telegraf service
#telegraf -config /usr/local/etc/telegraf.conf
--------------------------------------------------------------------
Consul
Consul is a distributed service mesh to connect, secure, and configure services across any runtime platform and public or private cloud
In this project consul container is used for configuration management and KV
Create the directory /consul/config/
Create the configuration file /consul/config/config.json
--------------------------------------------------------------------
Vault:
It is to store secures, stores, and tightly controls access to tokens, passwords, certificates, API keys
Our Grafana secrets are stored in vault container
Used file backed storage /vault/file
Configuration File /vault/config/vault.json
Update the configuration file
--------------------------------------------------------------------
Grafana:
Data visualization & Monitoring with support for Graphite, InfluxDB, Prometheus, Elasticsearch and many more databases.
In our project Grafana and consul template running in same container
Grafana conf file /etc/Grafana/“grafana.ini”
Template file /etc/Grafana/“grafana.ini.ctmpl”
Used Nginx for SSL
/etc/nginx
/etc/nginx/sites-enabled/default
Certificates stored in
/ etc/nginx/cert.crt
/etc/nginx/cert.key
Supervisor -
Used supervisor to run the services
Configuration file -> /etc/supervisor/conf.d/supervisord.conf
Consul-template command
#/bin/consul-template -consul-addr 'consul:8500' -template '/etc/grafana/grafana.ini.ctmpl:/etc/grafana/grafana.ini'
--------------------------------------------------------------------
InfluxDB
InfluxDB is an open-source time series database developed written in Go by InfluxData. InfluxDB is optimized for fast, high-availability storage and retrieval of time series data for metrics analysis
Created a Database and user
user=admin
password=<PASSWORD>
database=influx
--------------------------------------------------------------------
Troubleshooting:
If the git2consul container is not up, please run "docker-compose up -d" once again to bring it up
I have tried this task in Mac Laptop Docker engine, please use "localhost" for all configurations
--------------------------------------------------------------------
<file_sep>#!/usr/bin/env sh
/bin/consul-template -consul-addr 'consul:8500' -template '/etc/grafana/grafana.ini.ctmpl:/etc/grafana/grafana.ini'
| bd0b16f2ed572dab686ee16d6000a3e94e2041db | [
"Markdown",
"Shell",
"Dockerfile",
"YAML"
] | 4 | Dockerfile | vimalkrish/GICV-Version-2 | 7d2a44c95ae03d4923ffea101663e4248959616d | 8e67203e86ce8c8af4ba66f808dd03bcdc0497e2 | |
refs/heads/master | <file_sep>// slide-in menu JS
// get elements
const menuBtn = document.querySelector(".menu-button");
const slideMenu = document.querySelector(".slide-menu");
// add event listener
menuBtn.addEventListener("click", toggleMenu);
// set initial menuState
let menuVisible = false;
// functions
function toggleMenu() {
// toggles visibility of slide-in menu
if (!menuVisible) {
slideMenu.classList.add("show");
menuVisible = true;
} else {
slideMenu.classList.remove("show");
menuVisible = false;
}
}
| 358d9f512d20c316920ac7c4d3a22bfd29330bef | [
"JavaScript"
] | 1 | JavaScript | travisreynolds17/OnePagePencils | 041f8c9c9fdac0f17f932b6439d15fa19d775bf6 | edd9a9f8ab31d08006712a541deacfd4b3e4fdf6 | |
refs/heads/main | <repo_name>Rediet8abere/str-prob<file_sep>/README.md
# String Lib
![GitHub code size](https://img.shields.io/github/languages/code-size/rediet8abere/src-prob)
[npm](https://www.npmjs.com/~redifew)
### This library contains methods like:
- capitalizeFirst
- allCaps
- capitalizeWords
- capitalizeWords
- capitalizeHeadLine
- removeExtraSpace
- kebobCase
- snakeCase
- camelCase
- shift
- makeHashTag
- isEmpty
<file_sep>/umd/str-prob.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['str-prob'] = {}));
}(this, (function (exports) { 'use strict';
function capitalizeFirst(str) {
// capitalize first letter of a word
const newStr = str.charAt(0).toUpperCase() + str.slice(1);
return newStr
}
String.prototype.capitalizeFirst = function() {
return capitalizeFirst(this)
};
console.log(capitalizeFirst('hello'));
console.log('hello there'.capitalizeFirst());
function allCaps(str) {
return str.toUpperCase()
}
String.prototype.allCaps = function() {
return allCaps(this)
};
console.log(allCaps('hello'));
console.log('hello there'.allCaps());
function capitalizeWords(str) {
const strList = str.split(' ');
let newStr = '';
for (let i=0; i < strList.length; i++) {
newStr += capitalizeFirst(strList[i]) + ' ';
}
return newStr.trim()
}
String.prototype.capitalizeWords = function() {
return capitalizeWords(this)
};
console.log(capitalizeWords('we do all things right'));
console.log('In this world we do all things right'.capitalizeWords());
function capitalizeHeadLine(str) {
const prop = new Set(['the', 'in', 'a', 'an', 'and', 'but', 'for', 'at', 'by', 'from']);
const strList = str.split(' ');
let newStr = '';
for (let i=0; i < strList.length; i++) {
if (prop.has(strList[i])) {
newStr += strList[i] + ' ';
} else {
newStr += capitalizeFirst(strList[i]) + ' ';
}
}
return newStr.trim()
}
String.prototype.capitalizeHeadLine = function() {
return capitalizeHeadLine(this)
};
console.log(capitalizeHeadLine('we do all things in the name of god by the will of people'));
console.log('In this world we do all things right'.capitalizeHeadLine());
function removeExtraSpace(str){
const strTri = str.trim();
const strList = strTri.split(' ');
let newStr = '';
for (let i=0; i < strList.length; i++) {
if (strList[i] != '') {
newStr += strList[i] + ' ';
} else {
newStr += strList[i];
}
}
return newStr.trim()
}
String.prototype.removeExtraSpace = function() {
return removeExtraSpace(this)
};
console.log(removeExtraSpace(" Hello world! "));
console.log(" Hello world! ".removeExtraSpace());
function kebobCase(str) {
const strTri = str.trim();
const strList = strTri.split(" ");
return strList.join('-')
}
String.prototype.kebobCase = function() {
return kebobCase(this)
};
console.log(kebobCase(" Hello world "));
console.log(" Hello world ".kebobCase());
function snakeCase(str) {
const strTri = str.trim();
const strList = strTri.split(" ");
return strList.join('_')
}
String.prototype.snakeCase = function() {
return snakeCase(this)
};
console.log(snakeCase(" what the heck "));
console.log(" what the heck ".snakeCase());
function camelCase(str) {
const strTri = str.trim();
const strList = strTri.split(" ");
let newStr = '';
for (let i=0; i<strList.length; i++) {
if (i==0) {
newStr += strList[i].toLowerCase();
} else {
newStr += capitalizeFirst(strList[i]);
}
}
return newStr
}
String.prototype.camelCase = function() {
return camelCase(this)
};
console.log(camelCase('Camel Case'));
console.log('what the heck'.camelCase());
function shift(str, num) {
let newStr = str.slice(num) + str.slice(0, num);
return newStr
}
String.prototype.shift = function() {
return shift(this)
};
console.log(shift('hello world', 2));
console.log('Camel Case'.shift());
function makeHashTag(str) {
const strTri = capitalizeWords(str.trim());
const strList = strTri.split(" ");
return '#' + strList.join('')
}
String.prototype.makeHashTag = function() {
return makeHashTag(this)
};
console.log(makeHashTag('go for it'));
console.log('go for it'.makeHashTag());
function isEmpty(str) {
if (str.match(/[a-z]/i)) {
return false
} else if (str.match(/[A-Z]/i)) {
return false
} else if (str.match(/[0-9]/i)) {
return false
}
return true
}
String.prototype.isEmpty = function() {
return isEmpty(this)
};
console.log(isEmpty(''));
console.log(isEmpty('\n'));
console.log(isEmpty('\t'));
console.log(isEmpty('\r'));
console.log(isEmpty('hello 123'));
console.log('hello 123'.isEmpty());
exports.allCaps = allCaps;
exports.camelCase = camelCase;
exports.capitalizeFirst = capitalizeFirst;
exports.capitalizeHeadLine = capitalizeHeadLine;
exports.capitalizeWords = capitalizeWords;
exports.isEmpty = isEmpty;
exports.kebobCase = kebobCase;
exports.makeHashTag = makeHashTag;
exports.removeExtraSpace = removeExtraSpace;
exports.shift = shift;
exports.snakeCase = snakeCase;
Object.defineProperty(exports, '__esModule', { value: true });
})));
| 0ad8face780324c0f092ca204438136dceed1c26 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Rediet8abere/str-prob | a8c87450da736699b2b5148a9b469903a01c86a7 | 3e5dfbf90a8822b3da4359498f7bba453e0d4510 | |
refs/heads/master | <file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $table = 'employee';
protected $fillable = ['id','name','nric','department','temperature','quest1','quest2','quest3','quest4','quest5','quest6','quest7','quest8','quest9','quest10'];
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateVisitorTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('visitor', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('designation');
$table->string('company');
$table->string('visitingwho');
$table->string('quest11');
$table->string('quest12');
$table->string('quest13');
$table->string('quest14');
$table->string('quest15');
$table->string('quest16');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('visitor');
}
}
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeeTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employee', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('nric');
$table->string('department');
$table->string('temperature');
$table->string('quest1');
$table->string('quest2');
$table->string('quest3');
$table->string('quest4');
$table->string('quest5');
$table->string('quest6');
$table->string('quest7');
$table->string('quest8');
$table->string('quest9');
$table->string('quest10');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employee');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Visitor extends Model
{
protected $table = 'visitor';
protected $fillable = ['id','name','designation','company','visitingwho','quest1','quest2','quest3','quest4','quest5','quest6'];
}
<file_sep><?php
namespace App\Http\Controllers\TempCheck;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Temp;
use Carbon\Carbon;
use DB;
class TempCheckController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('tempcheck.create');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$checker = Carbon::today();
$user =Temp::where('name',$request->name)->whereDate('created_at', $checker)->first();
if(empty($user)) {
Temp::create([
'name' => $request->get('name'),
'temperature' => $request->get('temperature'),
]);
$checktemp = $request->temperature;
$checkname = $request->name;
// dd($checktemp);
return redirect()->back()->with('success','Done! Your temperature has been recorded')
->with('checktemp',$checktemp )->with('checkname',$checkname );
}
else{
return redirect()->back()->with('failed','Your temperature has been recorded for today');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App\Http\Controllers\Form;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Employee;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required',
'nric' => 'required',
'department' => 'required',
'temperature' => 'required',
'quest1' => 'required',
'quest2' => 'required',
'quest3' => 'required',
'quest4' => 'required',
'quest5' => 'required',
'quest6' => 'required',
'quest7' => 'required',
'quest8' => 'required',
'quest9' => 'required',
'quest10' => 'required',
],
[
'name.required' => 'The full name field is required',
'nric.required' => 'The staff NRIC field is required',
'department.required' => 'The department field is required.',
'temperature.required' => 'The temperature field is required.',
'quest1.required' => 'Please answer questions 1',
'quest2.required' => 'Please answer questions 2',
'quest3.required' => 'Please answer questions 3',
'quest4.required' => 'Please answer questions 4',
'quest5.required' => 'Please answer questions 4.1',
'quest6.required' => 'Please answer questions 4.2',
'quest7.required' => 'Please answer questions 4.3',
'quest8.required' => 'Please answer questions 4.4',
'quest9.required' => 'Please answer questions 4.5',
'quest10.required' =>'Please answer questions 5',
]);
Employee::create($request->all());
return redirect()->back()->with('success','Thank your for your time!');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
namespace App\Http\Controllers\Report;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Temp;
use Carbon\Carbon;
use DB;
class ReportController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$mytime = Carbon::now();
$recordstaff =Temp::whereDate('created_at','=',$mytime)->get();
return view ('report.index', compact('recordstaff'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if(is_null($request->from_date))
{
$mytime = Carbon::now();
$recordstaff = Temp::whereDate('created_at','=',$mytime)->get();
return view ('report.index', compact('recordstaff'));
}
else
{
$fromdate = Carbon::parse($request->from_date);
$todate = Carbon::parse($request->to_date)->addDays(1);
$recordstaff = Temp::whereBetween('created_at',array($fromdate, $todate))->get();
// dd($recordstaff);
return view ('report.index', compact('recordstaff','fromdate','todate'));
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
<file_sep><?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('tempcheck.create');
});
Route::resource('TempCheck','TempCheck\TempCheckController');
Route::resource('Report','Report\ReportController');
Route::resource('DeclarationForm','Form\FormController');
Route::resource('Employee','Form\EmployeeController');
Route::resource('Visitor','Form\VisitorController');
Route::resource('List','Form\ListController');
Route::resource('EmployeeQuestList','Quest\EmployeeQuestController');
Route::resource('VisitoreQuestList','Quest\VisitorQuestController');
| 69212e07d268d367baf2fe400aa0ecd01bf7aa7d | [
"PHP"
] | 8 | PHP | nazirulfitrifauzi/csc-covid19 | 21141725988d9ba41f01101a5bb30898068cbce9 | 6947fa50f6da63ab3e6f6623947742ac661f0427 | |
refs/heads/master | <repo_name>djghostghost/go-lesson-third-week<file_sep>/main.go
package main
import (
"context"
"fmt"
"golang.org/x/sync/errgroup"
"log"
"net/http"
"os"
"os/signal"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
eg, ctx := errgroup.WithContext(ctx)
srv := &http.Server{Addr: ":8040"}
eg.Go(func() error {
return serverApp(srv)
})
eg.Go(func() error {
<-ctx.Done()
fmt.Println("Shut down server")
return srv.Shutdown(ctx)
})
sigs := make(chan os.Signal, 1)
signal.Notify(sigs)
eg.Go(func() error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-sigs:
cancel()
}
}
})
if err := eg.Wait(); err != nil {
log.Fatal(err)
}
fmt.Println("All clear")
}
func serverApp(server *http.Server) error {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintf(writer, "Hello, World")
})
fmt.Println("App server start, Listen: 8040")
return server.ListenAndServe()
}
<file_sep>/go.mod
module github.com/djghostghost/go-lesson-third-week
go 1.16
require golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
| 7b98266f4018f36b168374a908891db02c38b0ee | [
"Go Module",
"Go"
] | 2 | Go | djghostghost/go-lesson-third-week | 13bfa8eb3d9d60f97c54b21cdd2284a53fa08136 | 9fa54f4a1b55434611448dad5813ce5b6928d04e | |
refs/heads/master | <repo_name>cmnf/sanji-ethernet-ui<file_sep>/src/component/form/container.component.js
import EthernetFormContainerController from './container.controller';
const EthernetFormContainerComponent = {
template: `<sanji-ethernet-form data="$ctrl.data" on-submit="$ctrl.onSave($event)"></sanji-ethernet-form>`,
controller: EthernetFormContainerController
};
export default EthernetFormContainerComponent;
| 4a86c5e10700e0f8bf64733c26588ec0b350f7a3 | [
"JavaScript"
] | 1 | JavaScript | cmnf/sanji-ethernet-ui | deae845ea9190daec70db5d933bd3157ef5a7b62 | 60eea723ab7cdf06f01d28c829efab9e4606e5b6 | |
refs/heads/master | <repo_name>nazarialireza/responsive-media-queries<file_sep>/src/js/responsive.js
// window.$ = window.jQuery = require('jquery');
// import * as $ from 'jquery';
import {$,jQuery} from 'jquery';
window.$ = $;
window.jQuery = jQuery;
export default $;
export { jQuery };
import '@popperjs/core';
import 'bootstrap';
import 'bootstrap/js/dist/dropdown';
console.log("Responsive ...")<file_sep>/README.md
# Responsive Media Queries
CSS media queries for mobile displays, here are CSS files which you can use them as
starting point for you custom CSS media queries or even use our custom template to
new project. all template here are available online freely, and we did just mix them
for our use cases and more fun.
## How to use
before anything, you can clone or download the project form the GitHub, then run
the following command to NPM dependencies: (windows console / CMD).
````
npm install
````
note: you need to have Node and NPM tools installed in your system before run the
command. to install please visit [Node Download Page](https://nodejs.org/en/download/).
## Run the server
After you had installed dependencies, you can run the following command to run the
server, and then open the localhost:5000 or 127.0.0.1:5000 in your browser.
````
npm run serve
````
| 3ed6a979c7e602c452f686f463e5040aa5b9513e | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | nazarialireza/responsive-media-queries | 0e60b1151071cc2d119b99c66d591568008dcfc9 | 2eae1e7adff8de64ccc3236d609954e027c9a77d | |
refs/heads/master | <file_sep>//
// FeedVC.swift
// WestPluto1
//
// Created by <NAME> on 1/17/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase
import SwiftKeychainWrapper
func admin() {
}
class FeedVC: UITableViewController {
@IBOutlet weak var WhatIamConsideringBuying: UITextField!
@IBOutlet weak var Education: UITextField!
override func viewDidLoad() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut))
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//override func didReceiveMemoryWarning() {
// super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
// }
// MARK: - Table view data source
//override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
//return 1
// }
// override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
//return 5
// }
//override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// return UITableViewCell()
//}
@IBAction func SubmitPressed(_ sender: Any) {
let databaseRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
databaseRef.child("Education").child(uid).setValue(self.Education.text!)
// The following line will save it in userDefault itself. And you dont have to call the whole UserDefault Everywhere
databaseRef.child("WhatIamConsideringBuying").child(uid).setValue(self.WhatIamConsideringBuying.text!)
self.performSegue(withIdentifier: "tohome", sender: nil)
}
func getUsers(){
usersCollection.getEducation{ (snapshot, _) in
let Education = snapshot!.Education
}
}
@objc func signOut (_sender: AnyObject) {
KeychainWrapper.standard.removeObject(forKey: "uid")
do {
try Auth.auth().signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// File.swift
// WestPluto1
//
// Created by <NAME> on 2018/03/10.
// Copyright © 2018 <NAME>. All rights reserved.
//
import Foundation
<file_sep>//
// ViewController.swift
// WestPluto1
//
// Created by <NAME> on 1/5/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
import UIKit
import Firebase
import SwiftKeychainWrapper
class ViewController: UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
var userUID: String!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
if let _ = KeychainWrapper.standard.string(forKey: "uid") {
self.performSegue(withIdentifier: "tohome", sender: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signInPressed(_ sender: Any) {
if let email = emailField.text, let password = passwordField.text {
Auth.auth().createUser(withEmail: email, password: <PASSWORD>) { (user, error) in
Auth.auth().signIn(withEmail: email, password: <PASSWORD>) { (user, error) in
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "tohome", sender: nil) }
if error != nil{
print("Incorrect")
let alert = UIAlertController(title: "Error", message: "Incorrect Email or Password.", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
else {
if let userID = user?.uid {
KeychainWrapper.standard.set((userID), forKey: "uid")
self.performSegue(withIdentifier: "tohome", sender: nil)
let databaseRef = Database.database().reference()
databaseRef.child("users").child(userID).setValue(self.emailField.text!)
}
}
}
}
}
}
}
<file_sep>//
// Constants.swift
// WestPluto1
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import SwiftKeychainWrapper
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase
var educationCache : String {
get {
return (UserDefaults.standard.string(forKey: "Education")!)
} set {
UserDefaults.standard.set(newValue, forKey: "Education")
}
}
var WhatIamConsideringBuyingCache : String {
get {
return (UserDefaults.standard.string(forKey: "WhatIamConsideringBuying")!)
} set {
UserDefaults.standard.set(newValue, forKey: "WhatIamConsideringBuying")
}
}
<file_sep>//
// homepage.swift
// WestPluto1
//
// Created by <NAME> on 5/21/19.
// Copyright © 2019 <NAME>. All rights reserved.
//
import Foundation
import UIKit
import SwiftKeychainWrapper
import Firebase
import CoreFoundation
import AVFoundation
import FirebaseDatabase
class homepage:UITableViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if snapshot.exists()
self.performSegue(withIdentifier: "toFeed", sender: nil)
}
override func viewDidLoad() {
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(signOut))
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func signOut (_sender: AnyObject) {
KeychainWrapper.standard.removeObject(forKey: "uid")
do {
try Auth.auth().signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
dismiss(animated: true, completion: nil)
}
}
| 760b9472433e26252bf4ba2d6ab20865a94995f6 | [
"Swift"
] | 5 | Swift | carlo190101martin/WP | b6c2423d24bcbd94ad35dbc874aec6bd8408c988 | 7324f393bae2bf0c5d8824d1a995485b98b667d5 | |
refs/heads/master | <repo_name>NoamRom89/WS-Goals<file_sep>/README.md
# WS-Goals
Targil 0 - Web Service
Edit by <NAME>
<file_sep>/Goals/index.js
var events = require('events');
var util = require('util');
var date = new Date();
util.inherits(Record, events.EventEmitter);
var logMsg ='';
function Record(){
this.goalsBalance = 0;
events.EventEmitter.call(this);
}
exports.log = function() {
return logMsg;
};
exports.createInstance = function (){
var record = new Record();
record.on('goal',displayGoals);
record.on('miss',displayMiss);
return record;
};
Record.prototype.goal = function(){
this.goalsBalance++;
this.emit('goal');
};
Record.prototype.miss = function(){
this.goalsBalance--;
this.emit('miss');
};
//-- The callbacks functions
function displayGoals(){
console.log('Ronaldo scored: ' + this.goalsBalance + ' goals');
logMsg += date.getDate() + ' Ronaldo scored: ' + this.goalsBalance + 'goals\n';
}
function displayMiss(){
console.log('Ronaldo missed, his balance now: ' + this.goalsBalance );
logMsg += date.getDate() + ' Ronaldo missed, his balance now: ' + this.goalsBalance + 'goals\n';
if(this.goalsBalance < 0){
console.log("Ronaldo in his lowest point of his life: " + this.goalsBalance);
logMsg += date.getDate() + ' Ronaldo in his lowest point of his life: ' + this.goalsBalance + 'goals\n';
}
}
| 0c99ff2f70f0ad9298c93aba133ab089b57e4f86 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | NoamRom89/WS-Goals | bf73fb92edfc3dd962b6b2a2766a21da768880a2 | 2c09d2bcf54251ffa37f27a48c2ef74adea7395f | |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms.DataVisualization.Charting;
namespace Graphic
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
// chart.Series.Clear();
double x1 = double.Parse(X1.Text);
double x2 = double.Parse(X2.Text);
double h = double.Parse(H.Text);
int N = (int)((x2 - x1) / h)+1;
double[] mas1 = new double[N];
double[] mas2 = new double[N];
chart.ChartAreas.Add(new ChartArea("Diagram"));
chart.Series.Add(new Series("Series1"));
chart.Series["Series1"].ChartArea = "Diagram";
chart.Series["Series1"].ChartType = SeriesChartType.Column;
double x = x1;
for(int i=0;i<N;i++)
{
mas1[i] = x;
mas2[i] = Math.Sqrt(x) + Math.Sin(4 * Math.PI * x);
x += h;
}
chart.Series["Series1"].Points.DataBindXY(mas1, mas2);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
| 765f58cc9c344e771b4d2e34207708a36c1aba12 | [
"C#"
] | 1 | C# | Mixa1997/Tbl | 5c559ec7d301ddc9f717567dd2afe6733e45e264 | c3e01d091b62591576a64d419aa9406da26b56ea | |
refs/heads/master | <repo_name>skylurker/learningAndroid<file_sep>/README.md
Tictactoe: Going through this Habrahabr tutorial http://habrahabr.ru/blogs/android_development/110247/
<file_sep>/Tictactoe/app/src/main/java/com/mycompany/tictactoe/WinnerCheckerVertical.java
package com.mycompany.tictactoe;
/**
* Created by skylurker on 10.07.15.
*/
/**
* This one checks whether we have a winner who's filled in a vertical line.
*/
public class WinnerCheckerVertical implements WinnerCheckerInterface {
private Game game;
// constructor
public WinnerCheckerVertical (Game game) {
this.game = game;
}
public Player checkWinner() {
Square[][] field = game.getField();
Player currentPlayer; // player whose sign is in the current cell
Player previousPlayer = null; // player whose sign was in the previous cell
for (int i = 0, rowsTotal = field.length; i < rowsTotal; i++) {
previousPlayer = null; //there is no "previous cell", this one is the first in the column
int successCounter = 1;
for (int j = 0, colsTotal = field[i].length; j < colsTotal; j++) {
// check which player's sign is in the cell
// it's field[j][i] because we're walking down the columns
// it doesn't spoil things much since we have a square matrix all the same
currentPlayer = field[j][i].getPlayer();
// if the current cell contains the same sign as the previous (which does exist) and both are not empty...
if (currentPlayer == previousPlayer && (currentPlayer != null && previousPlayer != null)) {
// ...then increase the counter value
successCounter++;
// if all the cells in the column are filled in by the same player, e.g. they all contain the same sign...
if (successCounter == rowsTotal) {
// then this player is the winner
return currentPlayer;
}
}
// before proceeding to check the next cell, set the current one to the "previous" state
previousPlayer = currentPlayer;
}
}
// if there is no winner
return null;
}
}
<file_sep>/Tictactoe/app/src/main/java/com/mycompany/tictactoe/Square.java
package com.mycompany.tictactoe;
/**
* Created by skylurker on 09.07.15.
*/
public class Square {
private Player player = null;
// fill the square with the player's 'signature'
public void fill(Player player) {
this.player = player;
}
/** TODO:
* Check whether there is a short if-then-else, such as
* player != null ? return true : return false
* or maybe
* player == null ? return false : return true
* Also check if the method works properly; it looks
* like there should be the ELSE keyword, shouldn't it
* AHHHH I forgot that the RETURN statement ensures the
* rest of the code gets omitted
* @return
*/
public boolean isFilled() {
if (player != null) {
return true;
}
return false;
}
public Player getPlayer() {
return player;
}
}
<file_sep>/Tictactoe/app/src/main/java/com/mycompany/tictactoe/MainActivity.java
package com.mycompany.tictactoe;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private TableLayout layout;
private Game game;
private Button[][] buttons = new Button[3][3];
//constructor
public MainActivity() {
game = new Game();
game.start();
}
// build the game field: get the game field and populate it with buttons
private void buildGameField(){
// get the field made of cells aka Squares
Square[][] field = game.getField();
for (int i = 0, rowsTotal = field.length; i < rowsTotal; i++ ) {
// create a table row
TableRow row = new TableRow(this);
for (int j = 0, colsTotal = field[i].length; j < colsTotal; j++) {
// assign a button to the cell
Button button = new Button(this);
buttons[i][j] = button;
// set a click listener
button.setOnClickListener(new Listener(i, j));
//add the button View to the row
row.addView(button, new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
/** TODO:
* un-hardcode the button widths and heights
*/
// button.setWidth(107);
button.setHeight(107);
}
// add the row View to the table
layout.addView(row, new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
layout.setStretchAllColumns(true);
}
public class Listener implements View.OnClickListener {
private int x = 0;
private int y = 0;
//constructor
public Listener (int x, int y) {
this.x = x;
this.y = y;
}
public void onClick(View view) {
Button button = (Button) view;
Game g = game;
Player player = g.getCurrentActivePlayer();
// if a player made his move, set his sign into the cell
if (g.makeTurn(x, y)){
button.setText(player.getName());
}
// check whether there is a winner
Player winner = g.checkWinner();
// if there is a winner, congrats!
if (winner != null) {
gameOver(winner);
}
// if there is no winner, but the field is already filled in completely
if (g.isFieldFilled()) {
gameOver();
}
}
}
// gameOver(Player player) and gameOver() are not the same!
private void gameOver(Player player) {
CharSequence text = "Player \"" + player.getName() + "\" won!";
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
game.reset();
refresh();
}
private void gameOver() {
CharSequence text = "Draw!";
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
game.reset();
refresh();
}
private void refresh() {
Square[][] field = game.getField();
for (int i = 0, rowsTotal = field.length; i < rowsTotal; i++) {
for (int j = 0, colsTotal = field[i].length; j < colsTotal; j++) {
if (field[i][j].getPlayer() == null) {
buttons[i][j].setText("");
} else { // no idea why do I need this one
buttons[i][j].setText(field[i][j].getPlayer().getName());
}
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (TableLayout) findViewById(R.id.main_layout);
buildGameField();
}
@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);
}
}
<file_sep>/Tictactoe/app/src/main/java/com/mycompany/tictactoe/WinnerCheckerDiagonalLeft.java
package com.mycompany.tictactoe;
/**
* Created by skylurker on 10.07.15.
*/
/**
* This one checks whether we have a winner who's filled in a vertical line.
*/
public class WinnerCheckerDiagonalLeft implements WinnerCheckerInterface {
private Game game;
// constructor
public WinnerCheckerDiagonalLeft (Game game) {
this.game = game;
}
public Player checkWinner() {
Square[][] field = game.getField();
Player currentPlayer; // player whose sign is in the current cell
Player previousPlayer = null; // player whose sign was in the previous cell
int successCounter = 1;
for (int i = 0, length = field.length; i < length; i++) {
// check which player's sign is in the cell
currentPlayer = field[i][i].getPlayer();
if (currentPlayer != null) {
// if the current cell contains the same sign as the previous one...
if (currentPlayer == previousPlayer) {
// ...then increase the counter value
successCounter++;
// if all the cells in the row are filled in by the same player, e.g. they all contain the same sign...
if (successCounter == length) {
// then this player is the winner
return currentPlayer;
}
}
}
// before proceeding to check the next cell, set the current one to the "previous" state
previousPlayer = currentPlayer;
}
// if there is no winner
return null;
}
}
| c964d33f8cb2605dbb5b83475bd8f076f52a156d | [
"Markdown",
"Java"
] | 5 | Markdown | skylurker/learningAndroid | d51e4150db74c150c9775819b6a323b87e7352e9 | 4ceaef3e4c2bdd0b452214281426ccfe7b38db49 | |
refs/heads/master | <repo_name>mtigas/1pass2keepassx<file_sep>/README.md
```shell
git clone https://github.com/mtigas/1pass2keepassx.git
cd 1pass2keepassx
bundle install
```
## Using: Current versions of 1Password
*(As of August 10, 2014.)*
Note that newer versions of 1Password actually use a folder
as the `.1pif` "file" and the actual legacy PIF-format file
is inside it. So you'd want to do something like this:
```shell
bundle exec ruby 1pass2keepass.rb ${YOURFILE}/data.1pif
```
That'll spit out the KeePassX XML to your console. What you
probably want is to save this to an XML. So redirect the output.
Putting it all together, you'd do something like this:
```shell
bundle exec ruby 1pass2keepass.rb ~/Desktop/pass.1pif/data.1pif > ~/Desktop/keepass.xml
```
## Using: Older versions of 1Password
Basically like above, but directly accessing the `.1pif` file.
```shell
bundle exec ruby 1pass2keepass.rb $YOURFILE
#i.e.:
bundle exec ruby 1pass2keepass.rb ~/Desktop/pass.1pif > ~/Desktop/keepass.xml
```
<file_sep>/1pass2keepass.rb
#!/usr/bin/ruby
=begin
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
=end
require 'rubygems'
require 'json'
require "rexml/document"
include REXML
require 'awesome_print'
def usage (message = nil)
if message
puts "ERROR: #{message}"
end
puts """Usage: 1pass2keepass.rb 1pass.1pif
Convert a 1Password export file to XML suitable for import into KeepassX.
"""
exit
end
input_file = ARGV[0]
unless ARGV[0]
usage
end
unless File.exists?(input_file)
usage "File '#{input_file}' does not exist"
end
lines = File.open(input_file).readlines()
lines.reject! {|l| l =~ /^\*\*\*/}
groups = {}
username = password = nil
lines.each do |line|
entry = JSON.parse(line)
if entry['trashed']
next
end
group_name = entry['typeName'].split('.')[-1]
if not groups.has_key?(group_name)
groups[group_name] = {}
end
title = entry['title']
case group_name
when 'Password','Database','UnixServer','Email','GenericAccount'
groups[group_name][title] = {
:url => nil,
:username => entry['secureContents']['username'],
:password => entry['secureContents']['<PASSWORD>'],
:creation => Time.at(entry['createdAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:lastmod => Time.at(entry['updatedAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:comment => entry['secureContents']['notesPlain'],
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
when 'SecureNote'
groups[group_name][title] = {
:url => nil,
:username => nil,
:password => nil,
:creation => Time.at(entry['createdAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:lastmod => Time.at(entry['updatedAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:comment => entry['secureContents']['notesPlain'],
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
when 'CreditCard'
groups[group_name][title] = {
:url => nil,
:username => entry['secureContents']['ccnum'],
:password => entry['<PASSWORD>'],
:creation => Time.at(entry['createdAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:lastmod => Time.at(entry['updatedAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:comment => "#{entry['secureContents']['expiry_mm']}/#{entry['secureContents']['expiry_yy']}",
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
when 'BankAccountUS'
groups[group_name][title] = {
:url => nil,
:username => entry['secureContents']['accountNo'],
:password => nil,
:creation => Time.at(entry['createdAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:lastmod => Time.at(entry['updatedAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:comment => "Bank Name: #{entry['secureContents']['bankName']}\nAccount: #{entry['secureContents']['accountNo']}\nRouting: #{entry['secureContents']['routingNo']}\nType: #{entry['secureContents']['accountType']}\nBank Address: #{entry['secureContents']['branchAddress']}\nBank Phone: #{entry['secureContents']['branchPhone']}\n",
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
when 'Regular', 'SavedSearch', 'Point'
next
when 'WebForm'
entry['secureContents']['fields'].each do |field|
case field['designation']
when 'username'
username = field['value']
when 'password'
password = field['value']
end
end
groups[group_name][title] = {
:url => entry['location'],
:username => username,
:password => <PASSWORD>,
:creation => Time.at(entry['createdAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:lastmod => Time.at(entry['updatedAt'].to_i).strftime("%Y-%m-%dT%H:%I:%S"),
:comment => entry['secureContents']['notesPlain'],
} unless (groups[group_name].has_key?(title) and groups[group_name][title]['updatedAt'].to_i > entry['updatedAt'].to_i)
username = password = nil
else
STDERR.puts "Don't know how to handle records of type #{entry['typeName']} yet."
end
end
doc = Document.new
database = doc.add_element 'database'
groups.each do |group_name, entries|
next if entries.empty?
group = database.add_element 'group'
case group_name
when 'Password'
group.add_element('title').text = 'Password'
group.add_element('icon').text = '0'
when 'BankAccountUS'
group.add_element('title').text = 'Bank Account'
group.add_element('icon').text = '66'
when 'CreditCard'
group.add_element('title').text = 'Credit Card'
group.add_element('icon').text = '66'
when 'SecureNote'
group.add_element('title').text = 'Secure Note'
group.add_element('icon').text = '54'
when 'WebForm'
group.add_element('title').text = 'Internet'
group.add_element('icon').text = '1'
when 'Email'
group.add_element('title').text = 'Email'
group.add_element('icon').text = '19'
when 'Database'
group.add_element('title').text = 'Database'
group.add_element('icon').text = '6'
when 'UnixServer'
group.add_element('title').text = 'Unix Server'
group.add_element('icon').text = '30'
when 'GenericAccount'
group.add_element('title').text = 'Generic Account'
group.add_element('icon').text = '20'
end
entries.each do |title, entry|
entry_node = group.add_element 'entry'
entry_node.add_element('title').text = title
entry_node.add_element('creation').text = entry[:creation]
entry_node.add_element('lastmod').text = entry[:lastmod]
entry_node.add_element('url').text = entry[:url]
["username", "<PASSWORD>", "comment"].each do |field|
if entry[field.to_sym]
node = entry_node.add_element(field)
node.text = ""
entry[field.to_sym].gsub(/\r/, '').split("\n").each_with_index do |t,i|
node.add_text t
if i != (entry[field.to_sym].gsub(/\r/, '').split("\n").size - 1)
node.add_element "br"
end
end
else
entry_node.add_element(field).text = entry[field.to_sym] || ""
end
end
end
end
doc << XMLDecl.new
formatter = REXML::Formatters::Pretty.new(2)
formatter.width = Float::INFINITY
formatter.compact = true
formatter.write(doc, $stdout)
<file_sep>/Gemfile
source 'https://rubygems.org'
ruby "2.1.2"
#gem "rexml"
gem "awesome_print"
| daa3ffd6f4d2a1877a515c49bf571f6450987682 | [
"Markdown",
"Ruby"
] | 3 | Markdown | mtigas/1pass2keepassx | 21205bc33341b4b7dac257df03ec04e231224d72 | 950048bdad67f48cd7b78e83b8b50ca48fe36054 | |
refs/heads/master | <repo_name>Rphmelo/Youtube-video-search-app<file_sep>/src/components/search_bar.js
import React, { Component } from "react";
class SearchBar extends Component {
constructor(props){
super(props);
this.state = { term: 'Starting Value'};
}
render() {
return (
<div className="search-bar search-container">
<form>
<input type="text" placeholder="Type something to search a video"
onChange={event => this.setState({term: event.target.value})}/>
<button type="button"
className="btn"
onClick={() => this.props.onSearchTermChange(this.state.term)}>
<span aria-hidden="true">Search</span>
</button>
</form>
</div>
)
}
}
export default SearchBar;<file_sep>/README.md
# Youtube Video Search App
A simple app for searching videos from youtube. Basically, you type something and the app brings the videos related to that.
It was written in React and Redux.
### Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
### Prerequisites
What things you need to install the software and how to install them
[Node - Click to download](https://nodejs.org/en/)
To use this app, you need to create an API key for using youtube API. To do that, access this turorial:
[Get a key from youtube API](https://developers.google.com/youtube/v3/getting-started?hl=pt-br)
After creating your API Key, you need to add in the index.js file:
``` javascript
// Your Youtube API Key goes here
const YOUTUBE_API_KEY = "";
```
#### Downloading this repository
Download this repo using the ```git clone``` command:
```
> git clone https://github.com/Rphmelo/Youtube-video-search-app.git
```
### Installing
A step by step series of examples that tell you how to get a development env running
Install the dependencies
```
npm install
```
After installing the dependencies, the given command will run the app:
```
npm start
```
## Built With
* [React](https://reactjs.org/)
* [Redux](https://redux.js.org/)
## Authors
* **<NAME>** - *Initial work* - [Rphmelo](https://github.com/Rphmelo)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
| 27243e2114a0499d4272605369be84d66f93e63b | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | Rphmelo/Youtube-video-search-app | 4b3a872a59e2a885627418f116900468b76c5b7c | f3a682683b7650063a259e90dcebbe8ef5e88f63 | |
refs/heads/master | <repo_name>SARATH365/shopping-android-app<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/CartItemAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.databinding.CartListItemBinding
import com.vishalgaur.shoppingapp.databinding.LayoutCircularLoaderBinding
class CartItemAdapter(
private val context: Context, items: List<UserData.CartItem>,
products: List<Product>, userLikes: List<String>
) : RecyclerView.Adapter<CartItemAdapter.ViewHolder>() {
lateinit var onClickListener: OnClickListener
var data: List<UserData.CartItem> = items
var proList: List<Product> = products
var likesList: List<String> = userLikes
inner class ViewHolder(private val binding: CartListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(itemData: UserData.CartItem) {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
val proData = proList.find { it.productId == itemData.productId } ?: Product()
binding.cartProductTitleTv.text = proData.name
binding.cartProductPriceTv.text =
context.getString(R.string.price_text, proData.price.toString())
if (proData.images.isNotEmpty()) {
val imgUrl = proData.images[0].toUri().buildUpon().scheme("https").build()
Glide.with(context)
.asBitmap()
.load(imgUrl)
.into(binding.productImageView)
binding.productImageView.clipToOutline = true
}
binding.cartProductQuantityTextView.text = itemData.quantity.toString()
if (likesList.contains(proData.productId)) {
binding.cartProductLikeBtn.setImageResource(R.drawable.liked_heart_drawable)
} else {
binding.cartProductLikeBtn.setImageResource(R.drawable.heart_icon_drawable)
}
binding.cartProductLikeBtn.setOnClickListener {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
if (!likesList.contains(proData.productId)) {
binding.cartProductLikeBtn.setImageResource(R.drawable.liked_heart_drawable)
} else {
binding.cartProductLikeBtn.setImageResource(R.drawable.heart_icon_drawable)
}
onClickListener.onLikeClick(proData.productId)
}
binding.cartProductDeleteBtn.setOnClickListener {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
onClickListener.onDeleteClick(itemData.itemId, binding.loaderLayout)
}
binding.cartProductPlusBtn.setOnClickListener {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
onClickListener.onPlusClick(itemData.itemId)
}
binding.cartProductMinusBtn.setOnClickListener {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
onClickListener.onMinusClick(itemData.itemId, itemData.quantity, binding.loaderLayout)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
CartListItemBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount() = data.size
interface OnClickListener {
fun onLikeClick(productId: String)
fun onDeleteClick(itemId: String, itemBinding: LayoutCircularLoaderBinding)
fun onPlusClick(itemId: String)
fun onMinusClick(itemId: String, currQuantity: Int, itemBinding: LayoutCircularLoaderBinding)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/OrderSuccessFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.os.CountDownTimer
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentOrderSuccessBinding
import com.vishalgaur.shoppingapp.viewModels.OrderViewModel
class OrderSuccessFragment : Fragment() {
private lateinit var binding: FragmentOrderSuccessBinding
private val orderViewModel: OrderViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentOrderSuccessBinding.inflate(layoutInflater)
binding.loaderLayout.loaderCard.visibility = View.VISIBLE
binding.loaderLayout.loadingMessage.text = getString(R.string.process_order_msg)
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.orderConstraintGroup.visibility = View.GONE
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.backToHomeBtn.setOnClickListener {
findNavController().navigate(R.id.action_orderSuccessFragment_to_homeFragment)
}
}
private fun setObservers() {
orderViewModel.orderStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.loaderLayout.loaderCard.visibility = View.VISIBLE
}
else -> {
binding.orderConstraintGroup.visibility = View.VISIBLE
binding.loaderLayout.loaderCard.visibility = View.GONE
binding.redirectHomeTimerTv.text =
getString(R.string.redirect_home_timer_text, "5")
countDownTimer.start()
}
}
}
}
private val countDownTimer = object : CountDownTimer(5000, 1000) {
override fun onTick(millisUntilFinished: Long) {
val sec = millisUntilFinished / 1000
binding.redirectHomeTimerTv.text =
getString(R.string.redirect_home_timer_text, sec.toString())
}
override fun onFinish() {
findNavController().navigate(R.id.action_orderSuccessFragment_to_homeFragment)
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/repository/AuthRepoInterface.kt
package com.vishalgaur.shoppingapp.data.source.repository
import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PhoneAuthCredential
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.SignUpErrors
interface AuthRepoInterface {
suspend fun refreshData()
suspend fun signUp(userData: UserData)
fun login(userData: UserData, rememberMe: Boolean)
suspend fun checkEmailAndMobile(email: String, mobile: String, context: Context): SignUpErrors?
suspend fun checkLogin(mobile: String, password: String): UserData?
suspend fun signOut()
suspend fun hardRefreshUserData()
suspend fun insertProductToLikes(productId: String, userId: String): Result<Boolean>
suspend fun removeProductFromLikes(productId: String, userId: String): Result<Boolean>
suspend fun insertAddress(newAddress: UserData.Address, userId: String): Result<Boolean>
suspend fun updateAddress(newAddress: UserData.Address, userId: String): Result<Boolean>
suspend fun deleteAddressById(addressId: String, userId: String): Result<Boolean>
suspend fun insertCartItemByUserId(cartItem: UserData.CartItem, userId: String): Result<Boolean>
suspend fun updateCartItemByUserId(cartItem: UserData.CartItem, userId: String): Result<Boolean>
suspend fun deleteCartItemByUserId(itemId: String, userId: String): Result<Boolean>
suspend fun placeOrder(newOrder: UserData.OrderItem, userId: String): Result<Boolean>
suspend fun setStatusOfOrder(orderId: String, userId: String, status: String): Result<Boolean>
suspend fun getOrdersByUserId(userId: String): Result<List<UserData.OrderItem>?>
suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?>
suspend fun getLikesByUserId(userId: String): Result<List<String>?>
suspend fun getUserData(userId: String): Result<UserData?>
fun getFirebaseAuth(): FirebaseAuth
fun signInWithPhoneAuthCredential(
credential: PhoneAuthCredential,
isUserLoggedIn: MutableLiveData<Boolean>,
context: Context
)
fun isRememberMeOn(): Boolean
}
<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/ui/home/ProductDetailsFragmentTest.kt
package com.vishalgaur.shoppingapp.ui.home
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.fragment.app.testing.FragmentScenario
import androidx.navigation.NavController
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.ServiceLocator
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.FakeAuthRepository
import com.vishalgaur.shoppingapp.data.source.FakeProductsRepository
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class ProductDetailsFragmentTest {
private lateinit var productDetailScenario: FragmentScenario<ProductDetailsFragment>
private lateinit var navController: NavController
private lateinit var sessionManager: ShoppingAppSessionManager
private lateinit var productsRepository: ProductsRepoInterface
private lateinit var authRepository: AuthRepoInterface
private val context = ApplicationProvider.getApplicationContext<ShoppingApplication>()
private val pro1 = Product(
"pro-owner1-shoe-101",
"Shoe Name 101",
"user1234selller",
"some description",
"Shoes",
250.0,
300.0,
listOf(5, 6, 7, 8),
listOf("Red", "Blue"),
listOf("http://image-ref-uri/shoe-101-01.jpg", "http://image-ref-uri/-shoe-101-02.jpg"),
2.5
)
private val userCustomer = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
ArrayList(),
ArrayList(),
ArrayList(),
"CUSTOMER"
)
private val userSeller = UserData(
"user1234selller",
"<NAME>",
"+919999988888",
"<EMAIL>",
"1234",
emptyList(),
emptyList(),
emptyList(),
"SELLER"
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
sessionManager = ShoppingAppSessionManager(context)
authRepository = FakeAuthRepository(sessionManager)
productsRepository = FakeProductsRepository()
ServiceLocator.productsRepository = productsRepository
}
@After
fun cleanUp() = runBlockingTest {
authRepository.signOut()
ServiceLocator.resetRepository()
}
private suspend fun insertProducts() {
productsRepository.insertProduct(pro1)
}
}
<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/UserDataSource.kt
package com.vishalgaur.shoppingapp.data.source
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.EmailMobileData
interface UserDataSource {
suspend fun addUser(userData: UserData)
suspend fun getUserById(userId: String): Result<UserData?>
fun updateEmailsAndMobiles(email: String, mobile: String) {}
suspend fun getEmailsAndMobiles(): EmailMobileData? {
return null
}
suspend fun getUserByMobileAndPassword(
mobile: String,
password: String
): MutableList<UserData> {
return mutableListOf()
}
suspend fun likeProduct(productId: String, userId: String) {}
suspend fun dislikeProduct(productId: String, userId: String) {}
suspend fun insertAddress(newAddress: UserData.Address, userId: String) {}
suspend fun updateAddress(newAddress: UserData.Address, userId: String) {}
suspend fun deleteAddress(addressId: String, userId: String) {}
suspend fun insertCartItem(newItem: UserData.CartItem, userId: String) {}
suspend fun updateCartItem(item: UserData.CartItem, userId: String) {}
suspend fun deleteCartItem(itemId: String, userId: String) {}
suspend fun placeOrder(newOrder: UserData.OrderItem, userId: String) {}
suspend fun setStatusOfOrderByUserId(orderId: String, userId: String, status: String) {}
suspend fun clearUser() {}
suspend fun getUserByMobile(phoneNumber: String): UserData? {
return null
}
suspend fun getOrdersByUserId(userId: String): Result<List<UserData.OrderItem>?>
suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?>
suspend fun getLikesByUserId(userId: String): Result<List<String>?>
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/AddEditProductFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.res.ColorStateList
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.chip.Chip
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.AddProductErrors
import com.vishalgaur.shoppingapp.data.utils.ShoeColors
import com.vishalgaur.shoppingapp.data.utils.ShoeSizes
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentAddEditProductBinding
import com.vishalgaur.shoppingapp.ui.AddProductViewErrors
import com.vishalgaur.shoppingapp.ui.MyOnFocusChangeListener
import com.vishalgaur.shoppingapp.viewModels.AddEditProductViewModel
import kotlin.properties.Delegates
private const val TAG = "AddProductFragment"
class AddEditProductFragment : Fragment() {
private lateinit var binding: FragmentAddEditProductBinding
private val viewModel by viewModels<AddEditProductViewModel>()
private val focusChangeListener = MyOnFocusChangeListener()
// arguments
private var isEdit by Delegates.notNull<Boolean>()
private lateinit var catName: String
private lateinit var productId: String
private var sizeList = mutableSetOf<Int>()
private var colorsList = mutableSetOf<String>()
private var imgList = mutableListOf<Uri>()
private val getImages =
registerForActivityResult(ActivityResultContracts.GetMultipleContents()) { result ->
imgList.addAll(result)
if (imgList.size > 3) {
imgList = imgList.subList(0, 3)
makeToast("Maximum 3 images are allowed!")
}
val adapter = context?.let { AddProductImagesAdapter(it, imgList) }
binding.addProImagesRv.adapter = adapter
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentAddEditProductBinding.inflate(layoutInflater)
isEdit = arguments?.getBoolean("isEdit") == true
catName = arguments?.getString("categoryName").toString()
productId = arguments?.getString("productId").toString()
initViewModel()
setViews()
setObservers()
return binding.root
}
private fun initViewModel() {
Log.d(TAG, "init view model, isedit = $isEdit")
viewModel.setIsEdit(isEdit)
if (isEdit) {
Log.d(TAG, "init view model, isedit = true, $productId")
viewModel.setProductData(productId)
} else {
Log.d(TAG, "init view model, isedit = false, $catName")
viewModel.setCategory(catName)
}
}
private fun setObservers() {
viewModel.errorStatus.observe(viewLifecycleOwner) { err ->
modifyErrors(err)
}
viewModel.dataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
StoreDataStatus.DONE -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
fillDataInAllViews()
}
else -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
makeToast("Error getting Data, Try Again!")
}
}
}
viewModel.addProductErrors.observe(viewLifecycleOwner) { status ->
when (status) {
AddProductErrors.ADDING -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
AddProductErrors.ERR_ADD_IMG -> {
setAddProductErrors(getString(R.string.add_product_error_img_upload))
}
AddProductErrors.ERR_ADD -> {
setAddProductErrors(getString(R.string.add_product_insert_error))
}
AddProductErrors.NONE -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
}
}
}
}
private fun setAddProductErrors(errText: String) {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.addProErrorTextView.visibility = View.VISIBLE
binding.addProErrorTextView.text = errText
}
private fun fillDataInAllViews() {
viewModel.productData.value?.let { product ->
Log.d(TAG, "fill data in views")
binding.addProAppBar.topAppBar.title = "Edit Product - ${product.name}"
binding.proNameEditText.setText(product.name)
binding.proPriceEditText.setText(product.price.toString())
binding.proMrpEditText.setText(product.mrp.toString())
binding.proDescEditText.setText(product.description)
imgList = product.images.map { it.toUri() } as MutableList<Uri>
val adapter = AddProductImagesAdapter(requireContext(), imgList)
binding.addProImagesRv.adapter = adapter
setShoeSizesChips(product.availableSizes)
setShoeColorsChips(product.availableColors)
binding.addProBtn.setText(R.string.edit_product_btn_text)
}
}
private fun setViews() {
Log.d(TAG, "set views")
if (!isEdit) {
binding.addProAppBar.topAppBar.title =
"Add Product - ${viewModel.selectedCategory.value}"
val adapter = AddProductImagesAdapter(requireContext(), imgList)
binding.addProImagesRv.adapter = adapter
}
binding.addProImagesBtn.setOnClickListener {
getImages.launch("image/*")
}
binding.addProAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
setShoeSizesChips()
setShoeColorsChips()
binding.addProErrorTextView.visibility = View.GONE
binding.proNameEditText.onFocusChangeListener = focusChangeListener
binding.proPriceEditText.onFocusChangeListener = focusChangeListener
binding.proMrpEditText.onFocusChangeListener = focusChangeListener
binding.proDescEditText.onFocusChangeListener = focusChangeListener
binding.addProBtn.setOnClickListener {
onAddProduct()
if (viewModel.errorStatus.value == AddProductViewErrors.NONE) {
viewModel.addProductErrors.observe(viewLifecycleOwner) { err ->
if (err == AddProductErrors.NONE) {
findNavController().navigate(R.id.action_addProductFragment_to_homeFragment)
}
}
}
}
}
private fun onAddProduct() {
val name = binding.proNameEditText.text.toString()
val price = binding.proPriceEditText.text.toString().toDoubleOrNull()
val mrp = binding.proMrpEditText.text.toString().toDoubleOrNull()
val desc = binding.proDescEditText.text.toString()
Log.d(
TAG,
"onAddProduct: Add product initiated, $name, $price, $mrp, $desc, $sizeList, $colorsList, $imgList"
)
viewModel.submitProduct(
name, price, mrp, desc, sizeList.toList(), colorsList.toList(), imgList
)
}
private fun setShoeSizesChips(shoeList: List<Int>? = emptyList()) {
binding.addProSizeChipGroup.apply {
removeAllViews()
for ((_, v) in ShoeSizes) {
val chip = Chip(context)
chip.id = v
chip.tag = v
chip.text = "$v"
chip.isCheckable = true
if (shoeList?.contains(v) == true) {
chip.isChecked = true
sizeList.add(chip.tag.toString().toInt())
}
chip.setOnCheckedChangeListener { buttonView, isChecked ->
val tag = buttonView.tag.toString().toInt()
if (!isChecked) {
sizeList.remove(tag)
} else {
sizeList.add(tag)
}
}
addView(chip)
}
invalidate()
}
}
private fun setShoeColorsChips(colorList: List<String>? = emptyList()) {
binding.addProColorChipGroup.apply {
removeAllViews()
var ind = 1
for ((k, v) in ShoeColors) {
val chip = Chip(context)
chip.id = ind
chip.tag = k
chip.chipStrokeColor = ColorStateList.valueOf(Color.BLACK)
chip.chipStrokeWidth = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
1F,
context.resources.displayMetrics
)
chip.chipBackgroundColor = ColorStateList.valueOf(Color.parseColor(v))
chip.isCheckable = true
if (colorList?.contains(k) == true) {
chip.isChecked = true
colorsList.add(chip.tag.toString())
}
chip.setOnCheckedChangeListener { buttonView, isChecked ->
val tag = buttonView.tag.toString()
if (!isChecked) {
colorsList.remove(tag)
} else {
colorsList.add(tag)
}
}
addView(chip)
ind++
}
invalidate()
}
}
private fun modifyErrors(err: AddProductViewErrors) {
when (err) {
AddProductViewErrors.NONE -> binding.addProErrorTextView.visibility = View.GONE
AddProductViewErrors.EMPTY -> {
binding.addProErrorTextView.visibility = View.VISIBLE
binding.addProErrorTextView.text = getString(R.string.add_product_error_string)
}
AddProductViewErrors.ERR_PRICE_0 -> {
binding.addProErrorTextView.visibility = View.VISIBLE
binding.addProErrorTextView.text = getString(R.string.add_pro_error_price_string)
}
}
}
private fun makeToast(text: String) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/local/ShoppingAppDatabase.kt
package com.vishalgaur.shoppingapp.data.source.local
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.DateTypeConvertors
import com.vishalgaur.shoppingapp.data.utils.ListTypeConverter
import com.vishalgaur.shoppingapp.data.utils.ObjectListTypeConvertor
@Database(entities = [UserData::class, Product::class], version = 2)
@TypeConverters(ListTypeConverter::class, ObjectListTypeConvertor::class, DateTypeConvertors::class)
abstract class ShoppingAppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
abstract fun productsDao(): ProductsDao
companion object {
@Volatile
private var INSTANCE: ShoppingAppDatabase? = null
fun getInstance(context: Context): ShoppingAppDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(
context.applicationContext,
ShoppingAppDatabase::class.java, "ShoppingAppDb"
)
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/UserData.kt
package com.vishalgaur.shoppingapp.data
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.vishalgaur.shoppingapp.data.utils.ObjectListTypeConvertor
import com.vishalgaur.shoppingapp.data.utils.OrderStatus
import com.vishalgaur.shoppingapp.data.utils.UserType
import kotlinx.android.parcel.Parcelize
import java.util.*
import kotlin.collections.ArrayList
@Parcelize
@Entity(tableName = "users")
data class UserData(
@PrimaryKey
var userId: String = "",
var name: String = "",
var mobile: String = "",
var email: String = "",
var password: String = "",
var likes: List<String> = ArrayList(),
@TypeConverters(ObjectListTypeConvertor::class)
var addresses: List<Address> = ArrayList(),
@TypeConverters(ObjectListTypeConvertor::class)
var cart: List<CartItem> = ArrayList(),
@TypeConverters(ObjectListTypeConvertor::class)
var orders: List<OrderItem> = ArrayList(),
var userType: String = UserType.CUSTOMER.name
) : Parcelable {
fun toHashMap(): HashMap<String, Any> {
return hashMapOf(
"userId" to userId,
"name" to name,
"email" to email,
"mobile" to mobile,
"password" to <PASSWORD>,
"likes" to likes,
"addresses" to addresses.map { it.toHashMap() },
"userType" to userType
)
}
@Parcelize
data class OrderItem(
var orderId: String = "",
var customerId: String = "",
var items: List<CartItem> = ArrayList(),
var itemsPrices: Map<String, Double> = mapOf(),
var deliveryAddress: Address = Address(),
var shippingCharges: Double = 0.0,
var paymentMethod: String = "",
var orderDate: Date = Date(),
var status: String = OrderStatus.CONFIRMED.name
) : Parcelable {
fun toHashMap(): HashMap<String, Any> {
return hashMapOf(
"orderId" to orderId,
"customerId" to customerId,
"items" to items.map { it.toHashMap() },
"itemsPrices" to itemsPrices,
"deliveryAddress" to deliveryAddress.toHashMap(),
"shippingCharges" to shippingCharges,
"paymentMethod" to paymentMethod,
"orderDate" to orderDate,
"status" to status
)
}
}
@Parcelize
data class Address(
var addressId: String = "",
var fName: String = "",
var lName: String = "",
var countryISOCode: String = "",
var streetAddress: String = "",
var streetAddress2: String = "",
var city: String = "",
var state: String = "",
var zipCode: String = "",
var phoneNumber: String = ""
) : Parcelable {
fun toHashMap(): HashMap<String, String> {
return hashMapOf(
"addressId" to addressId,
"fName" to fName,
"lName" to lName,
"countryISOCode" to countryISOCode,
"streetAddress" to streetAddress,
"streetAddress2" to streetAddress2,
"city" to city,
"state" to state,
"zipCode" to zipCode,
"phoneNumber" to phoneNumber
)
}
}
@Parcelize
data class CartItem(
var itemId: String = "",
var productId: String = "",
var ownerId: String = "",
var quantity: Int = 0,
var color: String?,
var size: Int?
) : Parcelable {
constructor() : this("", "", "", 0, "NA", -1)
fun toHashMap(): HashMap<String, Any> {
val hashMap = hashMapOf<String, Any>()
hashMap["itemId"] = itemId
hashMap["productId"] = productId
hashMap["ownerId"] = ownerId
hashMap["quantity"] = quantity
if (color != null)
hashMap["color"] = color!!
if (size != null)
hashMap["size"] = size!!
return hashMap
}
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/AppDatabaseTest.kt
package com.vishalgaur.shoppingapp
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.local.ProductsDao
import com.vishalgaur.shoppingapp.data.source.local.ShoppingAppDatabase
import com.vishalgaur.shoppingapp.data.source.local.UserDao
import kotlinx.coroutines.runBlocking
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AppDatabaseTest {
private val pro1 = Product(
"pro-owner1-shoe-101",
"Shoe Name 101",
"owner1",
"some description",
"Shoes",
250.0,
300.0,
listOf(5, 6, 7, 8),
listOf("Red", "Blue"),
listOf("http://image-ref-uri/shoe-101-01.jpg", "http://image-ref-uri/-shoe-101-02.jpg"),
2.5
)
private val pro2 = Product(
"pro-owner1-slipper-101",
"Slipper Name 101",
"owner1",
"some description",
"Slippers",
50.0,
80.0,
listOf(6, 7, 8),
listOf("Black", "Blue"),
listOf(
"http://image-ref-uri/-slipper-101-01.jpg",
"http://image-ref-uri/-slipper-101-02.jpg"
),
4.0
)
private lateinit var userDao: UserDao
private lateinit var productsDao: ProductsDao
private lateinit var appDb: ShoppingAppDatabase
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun createDb() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
appDb =
Room.inMemoryDatabaseBuilder(context, ShoppingAppDatabase::class.java)
.allowMainThreadQueries()
.build()
userDao = appDb.userDao()
productsDao = appDb.productsDao()
}
@After
fun closeDb() {
appDb.clearAllTables()
appDb.close()
}
@Test
fun insertAndGetUser() {
val user = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
ArrayList(),
ArrayList(),
ArrayList()
)
runBlocking {
userDao.insert(user)
val result = userDao.getById("sdjm43892yfh948ehod")
assertThat(result?.userId, `is`(user.userId))
}
}
@Test
fun noData_returnsNull() {
runBlocking {
val result = userDao.getById("1232")
assertThat(result, `is`(nullValue()))
}
}
@Test
fun insertClearUser_returnsNull() {
val user = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
emptyList(),
emptyList(),
emptyList()
)
runBlocking {
userDao.insert(user)
userDao.clear()
val result = userDao.getById("sdjm43892yfh948ehod")
assertThat(result, `is`(nullValue()))
}
}
@Test
fun insertAndGetProduct() {
runBlocking {
productsDao.insert(pro1)
val result = productsDao.getProductById(pro1.productId)
assertEquals(pro1, result)
}
}
@Test
fun insertClearProduct_returnsNull() = runBlocking {
productsDao.insert(pro1)
productsDao.deleteAllProducts()
val result = productsDao.getAllProducts()
assertEquals(0, result.size)
}
@Test
fun deleteProductById() = runBlocking {
productsDao.insert(pro2)
productsDao.deleteProductById(pro2.productId)
val result = productsDao.getProductById(pro2.productId)
assertThat(result, `is`(nullValue()))
}
@Test
fun noProducts_returnsEmptyList() = runBlocking {
val result = productsDao.getAllProducts()
assertThat(result.size, `is`(0))
}
@Test
fun deleteAllProducts_returnsEmptyList() = runBlocking {
productsDao.insert(pro2)
productsDao.deleteAllProducts()
val result = productsDao.getAllProducts()
assertThat(result.size, `is`(0))
}
@Test
fun getProductsByOwner_returnsData() = runBlocking {
productsDao.insert(pro2)
val result = productsDao.getProductsByOwnerId(pro2.owner)
assertThat(result.size, `is`(1))
}
@Test
fun insertMultipleProducts() = runBlocking {
productsDao.insertListOfProducts(listOf(pro1, pro2))
val result = productsDao.getAllProducts()
assertThat(result.size, `is`(2))
}
@Test
fun observeProducts_returnsLiveData() = runBlocking {
val initialRes = productsDao.observeProducts()
productsDao.insert(pro1)
val newValue = productsDao.observeProducts().getOrAwaitValue()
assertThat(initialRes.value, not(newValue))
assertThat(initialRes.value, `is`(nullValue()))
assertThat(newValue.size, `is`(1))
}
@Test
fun observeProductsByOwner_returnsLiveData() = runBlocking {
val initialRes = productsDao.observeProductsByOwner(pro1.owner)
productsDao.insert(pro1)
val newValue = productsDao.observeProductsByOwner(pro1.owner).getOrAwaitValue()
assertThat(initialRes.value, not(newValue))
assertThat(initialRes.value, `is`(nullValue()))
assertThat(newValue.size, `is`(1))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/Utils.kt
package com.vishalgaur.shoppingapp
import java.util.*
import java.util.regex.Pattern
import kotlin.math.roundToInt
const val MOB_ERROR_TEXT = "Enter valid mobile number!"
const val EMAIL_ERROR_TEXT = "Enter valid email address!"
const val ERR_INIT = "ERROR"
const val ERR_EMAIL = "_EMAIL"
const val ERR_MOBILE = "_MOBILE"
const val ERR_UPLOAD = "UploadErrorException"
internal fun isEmailValid(email: String): Boolean {
val EMAIL_PATTERN = Pattern.compile(
"\\s*[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
"\\@" +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
"(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
")+\\s*"
)
return if (email.isEmpty()) {
false
} else {
EMAIL_PATTERN.matcher(email).matches()
}
}
internal fun isPhoneValid(phone: String): Boolean {
val PHONE_PATTERN = Pattern.compile("^\\s*[6-9]\\d{9}\\s*\$")
return if (phone.isEmpty()) {
false
} else {
PHONE_PATTERN.matcher(phone).matches()
}
}
internal fun isZipCodeValid(zipCode: String): Boolean {
val ZIPCODE_PATTERN = Pattern.compile("^\\s*[1-9]\\d{5}\\s*\$")
return if (zipCode.isEmpty()) {
false
} else {
ZIPCODE_PATTERN.matcher(zipCode).matches()
}
}
internal fun getRandomString(length: Int, uNum: String, endLength: Int): String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
fun getStr(l: Int): String = (1..l).map { allowedChars.random() }.joinToString("")
return getStr(length) + uNum + getStr(endLength)
}
internal fun getProductId(ownerId: String, proCategory: String): String {
val uniqueId = UUID.randomUUID().toString()
return "pro-$proCategory-$ownerId-$uniqueId"
}
internal fun getOfferPercentage(costPrice: Double, sellingPrice: Double): Int {
if (costPrice == 0.0 || sellingPrice == 0.0 || costPrice <= sellingPrice)
return 0
val off = ((costPrice - sellingPrice) * 100) / costPrice
return off.roundToInt()
}
internal fun getAddressId(userId: String): String {
val uniqueId = UUID.randomUUID().toString()
return "$userId-$uniqueId"
}
<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/ui/home/HomeFragmentTest.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.core.view.isVisible
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.testing.TestNavHostController
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.UiController
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.RootMatchers.isDialog
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.vishalgaur.shoppingapp.*
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.FakeAuthRepository
import com.vishalgaur.shoppingapp.data.source.FakeProductsRepository
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.Matchers.`is`
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class HomeFragmentTest {
private lateinit var homeScenario: FragmentScenario<HomeFragment>
private lateinit var navController: NavController
private lateinit var sessionManager: ShoppingAppSessionManager
private lateinit var productsRepository: ProductsRepoInterface
private lateinit var authRepository: AuthRepoInterface
private val context = ApplicationProvider.getApplicationContext<ShoppingApplication>()
private val userCustomer = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
ArrayList(),
ArrayList(),
ArrayList(),
"CUSTOMER"
)
private val userSeller = UserData(
"user1234selller",
"<NAME>",
"+919999988888",
"<EMAIL>",
"1234",
emptyList(),
emptyList(),
emptyList(),
"SELLER"
)
private val pro1 = Product(
"pro-owner1-shoe-101",
"Shoe Name 101",
"user1234selller",
"some description",
"Shoes",
250.0,
300.0,
listOf(5, 6, 7, 8),
listOf("Red", "Blue"),
listOf("http://image-ref-uri/shoe-101-01.jpg", "http://image-ref-uri/-shoe-101-02.jpg"),
2.5
)
private val pro2 = Product(
"pro-owner1-slipper-101",
"Slipper Name 101",
"owner1",
"some description",
"Slippers",
50.0,
80.0,
listOf(6, 7, 8),
listOf("Black", "Blue"),
listOf(
"http://image-ref-uri/-slipper-101-01.jpg",
"http://image-ref-uri/-slipper-101-02.jpg"
),
4.0
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
sessionManager = ShoppingAppSessionManager(context)
authRepository = FakeAuthRepository(sessionManager)
productsRepository = FakeProductsRepository()
ServiceLocator.productsRepository = productsRepository
}
@After
fun cleanUp() = runBlockingTest {
authRepository.signOut()
ServiceLocator.resetRepository()
}
@Test
fun userCustomer_hideFABandEditDeleteButtons() = runBlockingTest {
insertProducts()
loginCustomer()
onView(withId(R.id.home_fab_add_product)).check(matches(withEffectiveVisibility(Visibility.GONE)))
//testing recyclerview items
onView(withId(R.id.products_recycler_view))
.perform(
RecyclerViewActions.actionOnItemAtPosition<ProductAdapter.ItemViewHolder>(
0,
object : RecyclerViewItemAction() {
override fun perform(uiController: UiController?, view: View) {
val editButton: ImageView = view.findViewById(R.id.product_edit_button)
val deleteButton: ImageView =
view.findViewById(R.id.product_delete_button)
assertThat(editButton.isVisible, `is`(false))
assertThat(deleteButton.isVisible, `is`(false))
}
})
)
}
@Test
fun userSeller_showFABandEditDeleteButtons() = runBlockingTest {
insertProducts()
loginSeller()
onView(withId(R.id.home_fab_add_product)).check(matches(withEffectiveVisibility(Visibility.VISIBLE)))
//testing recyclerview items
onView(withId(R.id.products_recycler_view))
.perform(
RecyclerViewActions.actionOnItemAtPosition<ProductAdapter.ItemViewHolder>(
0,
object : RecyclerViewItemAction() {
override fun perform(uiController: UiController?, view: View) {
val editButton: ImageView = view.findViewById(R.id.product_edit_button)
val deleteButton: ImageView =
view.findViewById(R.id.product_delete_button)
assertThat(editButton.isVisible, `is`(true))
assertThat(deleteButton.isVisible, `is`(true))
}
})
)
}
@Test
fun onFABClick_openCategoryDialog() {
loginSeller()
onView(withId(R.id.home_fab_add_product)).perform(click())
onView(withText(R.string.pro_cat_dialog_title)).inRoot(isDialog())
.check(matches(isDisplayed()))
}
@Test
fun onSelectCategory_openAddProductFragment() {
loginSeller()
onView(withId(R.id.home_fab_add_product)).perform(click())
onView(withText(R.string.pro_cat_dialog_ok_btn)).inRoot(isDialog())
.check(matches(isDisplayed())).perform(click())
assertThat(navController.currentDestination?.id, `is`(R.id.addEditProductFragment))
}
@Test
fun onFilterClick_openFilterDialog() = runBlockingTest{
insertProducts()
loginCustomer()
onView(withId(R.id.home_filter)).perform(click())
onView(withText("Shoes")).inRoot(isDialog())
.perform(click())
onView(withText(R.string.pro_cat_dialog_ok_btn)).inRoot(isDialog())
.perform(click())
onView(withId(R.id.products_recycler_view)).check(RecyclerViewItemCountAssertion(1))
}
@Test
fun onFilter_filterResults() {
loginCustomer()
onView(withId(R.id.home_filter)).perform(click())
onView(withText(R.string.pro_cat_dialog_title)).inRoot(isDialog())
.check(matches(isDisplayed()))
}
@Test
fun enterSearch_filtersResults() {
runBlocking {
insertProducts()
loginCustomer()
onView(withId(R.id.home_search_edit_text)).perform(typeText("slipper"))
delay(500)
onView(withId(R.id.products_recycler_view)).check(RecyclerViewItemCountAssertion(1))
}
}
private fun loginSeller() {
authRepository.login(userSeller, true)
ServiceLocator.authRepository = authRepository
setScenarioAndNav()
}
private fun loginCustomer() {
authRepository.login(userCustomer, true)
ServiceLocator.authRepository = authRepository
setScenarioAndNav()
}
private fun setScenarioAndNav() {
homeScenario = launchFragmentInContainer(Bundle(), R.style.Theme_ShoppingApp)
navController = TestNavHostController(context)
runOnUiThread {
navController.setGraph(R.navigation.home_nav_graph)
homeScenario.onFragment {
Navigation.setViewNavController(it.requireView(), navController)
}
}
}
private suspend fun insertProducts() {
productsRepository.insertProduct(pro1)
productsRepository.insertProduct(pro2)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/local/UserLocalDataSource.kt
package com.vishalgaur.shoppingapp.data.source.local
import android.util.Log
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.*
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.UserDataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class UserLocalDataSource internal constructor(
private val userDao: UserDao,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : UserDataSource {
override suspend fun addUser(userData: UserData) {
withContext(ioDispatcher) {
userDao.clear()
userDao.insert(userData)
}
}
override suspend fun getUserById(userId: String): Result<UserData?> =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
return@withContext Success(uData)
} else {
return@withContext Error(Exception("User Not Found!"))
}
} catch (e: Exception) {
return@withContext Error(e)
}
}
override suspend fun getUserByMobile(phoneNumber: String): UserData? =
withContext(ioDispatcher) {
try {
val uData = userDao.getByMobile(phoneNumber)
if (uData != null) {
return@withContext uData
} else {
return@withContext null
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onGetUser: Error Occurred, $e")
return@withContext null
}
}
override suspend fun getOrdersByUserId(userId: String): Result<List<UserData.OrderItem>?> =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val ordersList = uData.orders
return@withContext Success(ordersList)
} else {
return@withContext Error(Exception("User Not Found"))
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onGetOrders: Error Occurred, ${e.message}")
return@withContext Error(e)
}
}
override suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?> =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val addressList = uData.addresses
return@withContext Success(addressList)
} else {
return@withContext Error(Exception("User Not Found"))
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onGetAddress: Error Occurred, ${e.message}")
return@withContext Error(e)
}
}
override suspend fun getLikesByUserId(userId: String): Result<List<String>?> =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val likesList = uData.likes
return@withContext Success(likesList)
} else {
return@withContext Error(Exception("User Not Found"))
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onGetLikes: Error Occurred, ${e.message}")
return@withContext Error(e)
}
}
override suspend fun dislikeProduct(productId: String, userId: String) =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val likesList = uData.likes.toMutableList()
likesList.remove(productId)
uData.likes = likesList
userDao.updateUser(uData)
} else {
throw Exception("User Not Found")
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onGetLikes: Error Occurred, ${e.message}")
throw e
}
}
override suspend fun likeProduct(productId: String, userId: String) =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val likesList = uData.likes.toMutableList()
likesList.add(productId)
uData.likes = likesList
userDao.updateUser(uData)
} else {
throw Exception("User Not Found")
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onGetLikes: Error Occurred, ${e.message}")
throw e
}
}
override suspend fun insertCartItem(newItem: UserData.CartItem, userId: String) =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val cartItems = uData.cart.toMutableList()
cartItems.add(newItem)
uData.cart = cartItems
userDao.updateUser(uData)
} else {
throw Exception("User Not Found")
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onInsertCartItem: Error Occurred, ${e.message}")
throw e
}
}
override suspend fun updateCartItem(item: UserData.CartItem, userId: String) =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val cartItems = uData.cart.toMutableList()
val pos = cartItems.indexOfFirst { it.itemId == item.itemId }
if (pos >= 0) {
cartItems[pos] = item
}
uData.cart = cartItems
userDao.updateUser(uData)
} else {
throw Exception("User Not Found")
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onInsertCartItem: Error Occurred, ${e.message}")
throw e
}
}
override suspend fun deleteCartItem(itemId: String, userId: String) =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val cartItems = uData.cart.toMutableList()
val pos = cartItems.indexOfFirst { it.itemId == itemId }
if (pos >= 0) {
cartItems.removeAt(pos)
}
uData.cart = cartItems
userDao.updateUser(uData)
} else {
throw Exception("User Not Found")
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onInsertCartItem: Error Occurred, ${e.message}")
throw e
}
}
override suspend fun setStatusOfOrderByUserId(orderId: String, userId: String, status: String) =
withContext(ioDispatcher) {
try {
val uData = userDao.getById(userId)
if (uData != null) {
val orders = uData.orders.toMutableList()
val pos = orders.indexOfFirst { it.orderId == orderId }
if (pos >= 0) {
orders[pos].status = status
val custId = orders[pos].customerId
val custData = userDao.getById(custId)
if (custData != null) {
val orderList = custData.orders.toMutableList()
val idx = orderList.indexOfFirst { it.orderId == orderId }
if (idx >= 0) {
orderList[idx].status = status
}
custData.orders = orderList
userDao.updateUser(custData)
}
}
uData.orders = orders
userDao.updateUser(uData)
} else {
throw Exception("User Not Found")
}
} catch (e: Exception) {
Log.d("UserLocalSource", "onInsertCartItem: Error Occurred, ${e.message}")
throw e
}
}
override suspend fun clearUser() {
withContext(ioDispatcher) {
userDao.clear()
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/utils/Utils.kt
package com.vishalgaur.shoppingapp.data.utils
import java.util.*
enum class SignUpErrors { NONE, SERR }
enum class LogInErrors { NONE, LERR }
enum class AddProductErrors { NONE, ERR_ADD, ERR_ADD_IMG, ADDING }
enum class AddObjectStatus { DONE, ERR_ADD, ADDING }
enum class UserType { CUSTOMER, SELLER }
enum class OrderStatus { CONFIRMED, PACKAGING, PACKED, SHIPPING, SHIPPED, ARRIVING, DELIVERED }
enum class StoreDataStatus { LOADING, ERROR, DONE }
fun getISOCountriesMap(): Map<String, String> {
val result = mutableMapOf<String, String>()
val isoCountries = Locale.getISOCountries()
val countriesList = isoCountries.map { isoCountry ->
result[isoCountry] = Locale("", isoCountry).displayCountry
}
return result
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/ProductDetailsFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.annotation.SuppressLint
import android.app.Application
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.Typeface
import android.os.Bundle
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.setMargins
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.PagerSnapHelper
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.AddObjectStatus
import com.vishalgaur.shoppingapp.data.utils.ShoeColors
import com.vishalgaur.shoppingapp.data.utils.ShoeSizes
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentProductDetailsBinding
import com.vishalgaur.shoppingapp.ui.AddItemErrors
import com.vishalgaur.shoppingapp.ui.DotsIndicatorDecoration
import com.vishalgaur.shoppingapp.viewModels.ProductViewModel
class ProductDetailsFragment : Fragment() {
inner class ProductViewModelFactory(
private val productId: String,
private val application: Application
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ProductViewModel::class.java)) {
return ProductViewModel(productId, application) as T
}
throw IllegalArgumentException("Unknown ViewModel Class")
}
}
private lateinit var binding: FragmentProductDetailsBinding
private lateinit var viewModel: ProductViewModel
private var selectedSize: Int? = null
private var selectedColor: String? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentProductDetailsBinding.inflate(layoutInflater)
val productId = arguments?.getString("productId")
if (activity != null && productId != null) {
val viewModelFactory = ProductViewModelFactory(productId, requireActivity().application)
viewModel = ViewModelProvider(this, viewModelFactory).get(ProductViewModel::class.java)
}
if (viewModel.isSeller()) {
binding.proDetailsAddCartBtn.visibility = View.GONE
} else {
binding.proDetailsAddCartBtn.visibility = View.VISIBLE
binding.proDetailsAddCartBtn.setOnClickListener {
if (viewModel.isItemInCart.value == true) {
navigateToCartFragment()
} else {
onAddToCart()
if (viewModel.errorStatus.value?.isEmpty() == true) {
viewModel.addItemStatus.observe(viewLifecycleOwner) { status ->
if (status == AddObjectStatus.DONE) {
makeToast("Product Added To Cart")
viewModel.checkIfInCart()
}
}
}
}
}
}
binding.loaderLayout.loaderFrameLayout.background =
ResourcesCompat.getDrawable(resources, R.color.white, null)
binding.layoutViewsGroup.visibility = View.GONE
binding.proDetailsAddCartBtn.visibility = View.GONE
setObservers()
return binding.root
}
override fun onResume() {
super.onResume()
viewModel.setLike()
viewModel.checkIfInCart()
selectedSize = null
selectedColor = null
}
private fun setObservers() {
viewModel.dataStatus.observe(viewLifecycleOwner) {
when (it) {
StoreDataStatus.DONE -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.proDetailsLayout.visibility = View.VISIBLE
setViews()
}
else -> {
binding.proDetailsLayout.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
}
}
}
viewModel.isLiked.observe(viewLifecycleOwner) {
if (it == true) {
binding.proDetailsLikeBtn.setImageResource(R.drawable.liked_heart_drawable)
} else {
binding.proDetailsLikeBtn.setImageResource(R.drawable.heart_icon_drawable)
}
}
viewModel.isItemInCart.observe(viewLifecycleOwner) {
if (it == true) {
binding.proDetailsAddCartBtn.text =
getString(R.string.pro_details_go_to_cart_btn_text)
} else {
binding.proDetailsAddCartBtn.text =
getString(R.string.pro_details_add_to_cart_btn_text)
}
}
viewModel.errorStatus.observe(viewLifecycleOwner) {
if (it.isNotEmpty())
modifyErrors(it)
}
}
@SuppressLint("ResourceAsColor")
private fun modifyErrors(errList: List<AddItemErrors>) {
makeToast("Please Select Size and Color.")
if (!errList.isNullOrEmpty()) {
errList.forEach { err ->
when (err) {
AddItemErrors.ERROR_SIZE -> {
binding.proDetailsSelectSizeLabel.setTextColor(R.color.red_600)
}
AddItemErrors.ERROR_COLOR -> {
binding.proDetailsSelectColorLabel.setTextColor(R.color.red_600)
}
}
}
}
}
private fun setViews() {
binding.layoutViewsGroup.visibility = View.VISIBLE
binding.proDetailsAddCartBtn.visibility = View.VISIBLE
binding.addProAppBar.topAppBar.title = viewModel.productData.value?.name
binding.addProAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.addProAppBar.topAppBar.inflateMenu(R.menu.app_bar_menu)
binding.addProAppBar.topAppBar.overflowIcon?.setTint(
ContextCompat.getColor(
requireContext(),
R.color.gray
)
)
setImagesView()
binding.proDetailsTitleTv.text = viewModel.productData.value?.name ?: ""
binding.proDetailsLikeBtn.apply {
setOnClickListener {
viewModel.toggleLikeProduct()
}
}
binding.proDetailsRatingBar.rating = (viewModel.productData.value?.rating ?: 0.0).toFloat()
binding.proDetailsPriceTv.text = resources.getString(
R.string.pro_details_price_value,
viewModel.productData.value?.price.toString()
)
setShoeSizeButtons()
setShoeColorsButtons()
binding.proDetailsSpecificsText.text = viewModel.productData.value?.description ?: ""
}
private fun onAddToCart() {
viewModel.addToCart(selectedSize, selectedColor)
}
private fun navigateToCartFragment() {
findNavController().navigate(R.id.action_productDetailsFragment_to_cartFragment)
}
private fun makeToast(text: String) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show()
}
private fun setImagesView() {
if (context != null) {
binding.proDetailsImagesRecyclerview.isNestedScrollingEnabled = false
val adapter = ProductImagesAdapter(
requireContext(),
viewModel.productData.value?.images ?: emptyList()
)
binding.proDetailsImagesRecyclerview.adapter = adapter
val rad = resources.getDimension(R.dimen.radius)
val dotsHeight = resources.getDimensionPixelSize(R.dimen.dots_height)
val inactiveColor = ContextCompat.getColor(requireContext(), R.color.gray)
val activeColor = ContextCompat.getColor(requireContext(), R.color.blue_accent_300)
val itemDecoration =
DotsIndicatorDecoration(rad, rad * 4, dotsHeight, inactiveColor, activeColor)
binding.proDetailsImagesRecyclerview.addItemDecoration(itemDecoration)
PagerSnapHelper().attachToRecyclerView(binding.proDetailsImagesRecyclerview)
}
}
private fun setShoeSizeButtons() {
binding.proDetailsSizesRadioGroup.apply {
for ((_, v) in ShoeSizes) {
if (viewModel.productData.value?.availableSizes?.contains(v) == true) {
val radioButton = RadioButton(context)
radioButton.id = v
radioButton.tag = v
val param =
binding.proDetailsSizesRadioGroup.layoutParams as ViewGroup.MarginLayoutParams
param.setMargins(resources.getDimensionPixelSize(R.dimen.radio_margin_size))
param.width = ViewGroup.LayoutParams.WRAP_CONTENT
param.height = ViewGroup.LayoutParams.WRAP_CONTENT
radioButton.layoutParams = param
radioButton.background =
ContextCompat.getDrawable(context, R.drawable.radio_selector)
radioButton.setButtonDrawable(R.color.transparent)
radioButton.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F)
radioButton.setTextColor(Color.BLACK)
radioButton.setTypeface(null, Typeface.BOLD)
radioButton.textAlignment = View.TEXT_ALIGNMENT_CENTER
radioButton.text = "$v"
radioButton.setOnCheckedChangeListener { buttonView, isChecked ->
val tag = buttonView.tag.toString().toInt()
if (isChecked) {
selectedSize = tag
}
}
addView(radioButton)
}
}
invalidate()
}
}
private fun setShoeColorsButtons() {
binding.proDetailsColorsRadioGroup.apply {
var ind = 1
for ((k, v) in ShoeColors) {
if (viewModel.productData.value?.availableColors?.contains(k) == true) {
val radioButton = RadioButton(context)
radioButton.id = ind
radioButton.tag = k
val param =
binding.proDetailsColorsRadioGroup.layoutParams as ViewGroup.MarginLayoutParams
param.setMargins(resources.getDimensionPixelSize(R.dimen.radio_margin_size))
param.width = ViewGroup.LayoutParams.WRAP_CONTENT
param.height = ViewGroup.LayoutParams.WRAP_CONTENT
radioButton.layoutParams = param
radioButton.background =
ContextCompat.getDrawable(context, R.drawable.color_radio_selector)
radioButton.setButtonDrawable(R.color.transparent)
radioButton.backgroundTintList = ColorStateList.valueOf(Color.parseColor(v))
if (k == "white") {
radioButton.backgroundTintMode = PorterDuff.Mode.MULTIPLY
} else {
radioButton.backgroundTintMode = PorterDuff.Mode.ADD
}
radioButton.setOnCheckedChangeListener { buttonView, isChecked ->
val tag = buttonView.tag.toString()
if (isChecked) {
selectedColor = tag
}
}
addView(radioButton)
ind++
}
}
invalidate()
}
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/viewModels/AddEditAddressViewModelTest.kt
package com.vishalgaur.shoppingapp.viewModels
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.ServiceLocator
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.FakeAuthRepository
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.getOrAwaitValue
import com.vishalgaur.shoppingapp.ui.AddAddressViewErrors
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class AddEditAddressViewModelTest {
private lateinit var addEditAddressViewModel: AddEditAddressViewModel
private lateinit var authRepository: AuthRepoInterface
val user = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
ArrayList(),
ArrayList(),
ArrayList()
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
val context = ApplicationProvider.getApplicationContext<ShoppingApplication>()
val sessionManager = ShoppingAppSessionManager(context)
authRepository = FakeAuthRepository(sessionManager)
authRepository.login(user, true)
ServiceLocator.authRepository = authRepository
addEditAddressViewModel = AddEditAddressViewModel(context)
}
@After
fun cleanUp() = runBlockingTest {
ServiceLocator.resetRepository()
}
@Test
fun setIsEdit_setsValue() {
runBlockingTest {
addEditAddressViewModel.setIsEdit(false)
val res = addEditAddressViewModel.isEdit.getOrAwaitValue()
assertThat(res, `is`(false))
}
}
@Test
fun setAddressData_setsData() = runBlockingTest {
val address = UserData.Address(
"add-id-121",
"adg",
"shgd",
"IN",
"sfhg45eyh",
"",
"kanpuit",
"up",
"309890",
"9999988558"
)
authRepository.insertAddress(address, user.userId)
addEditAddressViewModel.setAddressData(address.addressId)
val result = addEditAddressViewModel.addressData.getOrAwaitValue()
assertThat(result, `is`(address))
}
@Test
fun submitAddress_emptyForm_returnsError() {
val fname = "adg"
val lname = ""
val code = "IN"
val streetAdd = "sfhg45eyh"
val streetAdd2 = ""
val city = ""
val state = "up"
val zip = "309890"
val phone = "9999988558"
addEditAddressViewModel.submitAddress(
code,
fname,
lname,
streetAdd,
streetAdd2,
city,
state,
zip,
phone
)
val result = addEditAddressViewModel.errorStatus.getOrAwaitValue()
assertThat(result.size, `is`(greaterThan(0)))
assertThat(result.contains(AddAddressViewErrors.ERR_CITY_EMPTY), `is`(true))
}
@Test
fun submitAddress_invalidZipcode_returnsError() {
val fname = "adg"
val lname = "serdg"
val code = "IN"
val streetAdd = "sfhg45eyh"
val streetAdd2 = ""
val city = "sfhg"
val state = "up"
val zip = "30990"
val phone = "9999988558"
addEditAddressViewModel.submitAddress(
code,
fname,
lname,
streetAdd,
streetAdd2,
city,
state,
zip,
phone
)
val result = addEditAddressViewModel.errorStatus.getOrAwaitValue()
assertThat(result.size, `is`(greaterThan(0)))
assertThat(result.contains(AddAddressViewErrors.ERR_ZIP_INVALID), `is`(true))
}
@Test
fun submitAddress_invalidPhone_returnsError() {
val fname = "adg"
val lname = "serdg"
val code = "IN"
val streetAdd = "sfhg45eyh"
val streetAdd2 = ""
val city = "sfhg"
val state = "up"
val zip = "309903"
val phone = "9999988efg558"
addEditAddressViewModel.submitAddress(
code,
fname,
lname,
streetAdd,
streetAdd2,
city,
state,
zip,
phone
)
val result = addEditAddressViewModel.errorStatus.getOrAwaitValue()
assertThat(result.size, `is`(greaterThan(0)))
assertThat(result.contains(AddAddressViewErrors.ERR_PHONE_INVALID), `is`(true))
}
@Test
fun submitAddress_validData_returnsNoError() {
val fname = "adg"
val lname = "serdg"
val code = "IN"
val streetAdd = "sfhg45eyh"
val streetAdd2 = ""
val city = "sfhg"
val state = "up"
val zip = "302203"
val phone = "9879988558"
addEditAddressViewModel.submitAddress(
code,
fname,
lname,
streetAdd,
streetAdd2,
city,
state,
zip,
phone
)
val result = addEditAddressViewModel.errorStatus.getOrAwaitValue()
assertThat(result.size, `is`(0))
val resData = addEditAddressViewModel.newAddressData.getOrAwaitValue()
assertThat(resData, `is`(notNullValue()))
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/viewModels/ProductViewModelTest.kt
package com.vishalgaur.shoppingapp.viewModels
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.ServiceLocator
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.FakeAuthRepository
import com.vishalgaur.shoppingapp.data.source.FakeProductsRepository
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import com.vishalgaur.shoppingapp.getOrAwaitValue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class ProductViewModelTest {
private lateinit var productViewModel: ProductViewModel
private lateinit var productId: String
private lateinit var productsRepository: ProductsRepoInterface
private lateinit var authRepository: AuthRepoInterface
val user = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
ArrayList(),
ArrayList(),
ArrayList()
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
productsRepository = FakeProductsRepository()
val sessionManager = ShoppingAppSessionManager(ApplicationProvider.getApplicationContext())
authRepository = FakeAuthRepository(sessionManager)
authRepository.login(user, true)
ServiceLocator.productsRepository = productsRepository
ServiceLocator.authRepository = authRepository
productId = "pro-shoes-wofwopjf-1"
productViewModel = ProductViewModel(productId, ApplicationProvider.getApplicationContext())
}
@After
fun cleanUp() = runBlockingTest {
ServiceLocator.resetRepository()
}
@Test
fun toggleLikeProduct_false_true() {
val result1 = productViewModel.isLiked.value
runBlocking {
productViewModel.toggleLikeProduct()
delay(1000)
val result2 = productViewModel.isLiked.getOrAwaitValue()
assertThat(result1, not(result2))
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/ProductAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.databinding.LayoutHomeAdBinding
import com.vishalgaur.shoppingapp.databinding.ProductsListItemBinding
import com.vishalgaur.shoppingapp.getOfferPercentage
class ProductAdapter(proList: List<Any>, userLikes: List<String>, private val context: Context) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var data = proList
var likesList = userLikes
lateinit var onClickListener: OnClickListener
lateinit var bindImageButtons: BindImageButtons
private val sessionManager = ShoppingAppSessionManager(context)
inner class ItemViewHolder(binding: ProductsListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
private val proName = binding.productNameTv
private val proPrice = binding.productPriceTv
private val productCard = binding.productCard
private val productImage = binding.productImageView
private val proDeleteButton = binding.productDeleteButton
private val proEditBtn = binding.productEditButton
private val proMrp = binding.productActualPriceTv
private val proOffer = binding.productOfferValueTv
private val proRatingBar = binding.productRatingBar
private val proLikeButton = binding.productLikeCheckbox
private val proCartButton = binding.productAddToCartButton
fun bind(productData: Product) {
productCard.setOnClickListener {
onClickListener.onClick(productData)
}
proName.text = productData.name
proPrice.text =
context.getString(R.string.pro_details_price_value, productData.price.toString())
proRatingBar.rating = productData.rating.toFloat()
proMrp.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
proMrp.text =
context.getString(
R.string.pro_details_actual_strike_value,
productData.mrp.toString()
)
proOffer.text = context.getString(
R.string.pro_offer_precent_text,
getOfferPercentage(productData.mrp, productData.price).toString()
)
if (productData.images.isNotEmpty()) {
val imgUrl = productData.images[0].toUri().buildUpon().scheme("https").build()
Glide.with(context)
.asBitmap()
.load(imgUrl)
.into(productImage)
productImage.clipToOutline = true
}
proLikeButton.isChecked = likesList.contains(productData.productId)
if (sessionManager.isUserSeller()) {
proLikeButton.visibility = View.GONE
proCartButton.visibility = View.GONE
proEditBtn.setOnClickListener {
onClickListener.onEditClick(productData.productId)
}
proDeleteButton.setOnClickListener {
onClickListener.onDeleteClick(productData)
}
} else {
proEditBtn.visibility = View.GONE
proDeleteButton.visibility = View.GONE
bindImageButtons.setLikeButton(productData.productId, proLikeButton)
bindImageButtons.setCartButton(productData.productId, proCartButton)
proLikeButton.setOnCheckedChangeListener { _, _ ->
}
proLikeButton.setOnClickListener {
onClickListener.onLikeClick(productData.productId)
}
proCartButton.setOnClickListener {
onClickListener.onAddToCartClick(productData)
}
}
}
}
inner class AdViewHolder(binding: LayoutHomeAdBinding) : RecyclerView.ViewHolder(binding.root) {
val adImageView: ImageView = binding.adImageView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_AD -> AdViewHolder(
LayoutHomeAdBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
else -> ItemViewHolder(
ProductsListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (val proData = data[position]) {
is Int -> (holder as AdViewHolder).adImageView.setImageResource(proData)
is Product -> (holder as ItemViewHolder).bind(proData)
}
}
override fun getItemCount(): Int = data.size
companion object {
const val VIEW_TYPE_PRODUCT = 1
const val VIEW_TYPE_AD = 2
}
override fun getItemViewType(position: Int): Int {
return when (data[position]) {
is Int -> VIEW_TYPE_AD
is Product -> VIEW_TYPE_PRODUCT
else -> VIEW_TYPE_PRODUCT
}
}
interface BindImageButtons {
fun setLikeButton(productId: String, button: CheckBox)
fun setCartButton(productId: String, imgView: ImageView)
}
interface OnClickListener {
fun onClick(productData: Product)
fun onDeleteClick(productData: Product)
fun onEditClick(productId: String) {}
fun onLikeClick(productId: String) {}
fun onAddToCartClick(productData: Product) {}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/loginSignup/LoginSignupActivity.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.vishalgaur.shoppingapp.R
class LoginSignupActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/loginSignup/SignupFragment.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.EMAIL_ERROR_TEXT
import com.vishalgaur.shoppingapp.MOB_ERROR_TEXT
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.SignUpErrors
import com.vishalgaur.shoppingapp.databinding.FragmentSignupBinding
import com.vishalgaur.shoppingapp.ui.SignUpViewErrors
class SignupFragment : LoginSignupBaseFragment<FragmentSignupBinding>() {
override fun setViewBinding(): FragmentSignupBinding {
return FragmentSignupBinding.inflate(layoutInflater)
}
override fun observeView() {
super.observeView()
viewModel.errorStatus.observe(viewLifecycleOwner) { err ->
modifyErrors(err)
}
}
override fun setUpViews() {
super.setUpViews()
binding.signupErrorTextView.visibility = View.GONE
binding.signupNameEditText.onFocusChangeListener = focusChangeListener
binding.signupMobileEditText.onFocusChangeListener = focusChangeListener
binding.signupEmailEditText.onFocusChangeListener = focusChangeListener
binding.signupPasswordEditText.onFocusChangeListener = focusChangeListener
binding.signupCnfPasswordEditText.onFocusChangeListener = focusChangeListener
binding.signupSignupBtn.setOnClickListener(object : OnClickListener {
override fun onClick(v: View?) {
onSignUp()
if (viewModel.errorStatus.value == SignUpViewErrors.NONE) {
viewModel.signErrorStatus.observe(viewLifecycleOwner) {
if (it == SignUpErrors.NONE) {
val bundle = bundleOf("uData" to viewModel.userData.value)
launchOtpActivity(getString(R.string.signup_fragment_label), bundle)
}
}
}
}
})
setUpClickableLoginText()
}
private fun setUpClickableLoginText() {
val loginText = getString(R.string.signup_login_text)
val ss = SpannableString(loginText)
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
findNavController().navigate(R.id.action_signup_to_login)
}
}
ss.setSpan(clickableSpan, 25, 31, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
binding.signupLoginTextView.apply {
text = ss
movementMethod = LinkMovementMethod.getInstance()
}
}
private fun onSignUp() {
val name = binding.signupNameEditText.text.toString()
val mobile = binding.signupMobileEditText.text.toString()
val email = binding.signupEmailEditText.text.toString()
val password1 = binding.signupPasswordEditText.text.toString()
val password2 = binding.signupCnfPasswordEditText.text.toString()
val isAccepted = binding.signupPolicySwitch.isChecked
val isSeller = binding.signupSellerSwitch.isChecked
viewModel.signUpSubmitData(name, mobile, email, password1, <PASSWORD>, isAccepted, isSeller)
}
private fun modifyErrors(err: SignUpViewErrors) {
when (err) {
SignUpViewErrors.NONE -> setEditTextsError()
SignUpViewErrors.ERR_EMAIL -> setEditTextsError(emailError = EMAIL_ERROR_TEXT)
SignUpViewErrors.ERR_MOBILE -> setEditTextsError(mobError = MOB_ERROR_TEXT)
SignUpViewErrors.ERR_EMAIL_MOBILE -> setEditTextsError(EMAIL_ERROR_TEXT, MOB_ERROR_TEXT)
SignUpViewErrors.ERR_EMPTY -> setErrorText("Fill all details.")
SignUpViewErrors.ERR_NOT_ACC -> setErrorText("Accept the Terms.")
SignUpViewErrors.ERR_PWD12NS -> setErrorText("Both passwords are not same!")
}
}
private fun setErrorText(errText: String?) {
binding.signupErrorTextView.visibility = View.VISIBLE
if (errText != null) {
binding.signupErrorTextView.text = errText
}
}
private fun setEditTextsError(emailError: String? = null, mobError: String? = null) {
binding.signupEmailEditText.error = emailError
binding.signupMobileEditText.error = mobError
binding.signupErrorTextView.visibility = View.GONE
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/ui/loginSignup/LoginFragmentTest.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.testing.TestNavHostController
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.test.platform.app.InstrumentationRegistry
import com.vishalgaur.shoppingapp.MOB_ERROR_TEXT
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.clickClickableSpan
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import org.hamcrest.Matchers.`is`
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class LoginFragmentTest {
private lateinit var loginScenario: FragmentScenario<LoginFragment>
private lateinit var navController: NavController
private lateinit var sessionManager: ShoppingAppSessionManager
@Before
fun setUp() {
sessionManager = ShoppingAppSessionManager(ApplicationProvider.getApplicationContext())
sessionManager.logoutFromSession()
loginScenario = launchFragmentInContainer(themeResId = R.style.Theme_ShoppingApp)
navController = TestNavHostController(ApplicationProvider.getApplicationContext())
runOnUiThread {
navController.setGraph(R.navigation.signup_nav_graph)
loginScenario.onFragment {
Navigation.setViewNavController(it.requireView(), navController)
}
}
}
@Test
fun useAppContext() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
Assert.assertEquals("com.vishalgaur.shoppingapp", context.packageName)
}
@Test
fun userCanEnterMobile() {
insertInMobileEditText("8976527465")
}
@Test
fun userCanEnterPassword() {
insertInPwdEditText("<PASSWORD>")
}
@Test
fun userCanClickRemSwitch() {
clickRememberSwitch()
}
@Test
fun userCanClickSignUpText() {
clickSignUpText()
}
@Test
fun userCanClickForgotTextView() {
clickForgotTextView()
}
@Test
fun userCanClickLoginButton() {
clickLoginButton()
}
@Test
fun onSignUpClick_navigateToSignUpFragment() {
clickSignUpText()
assertThat(navController.currentDestination?.id, `is`(R.id.SignupFragment))
}
@Test
fun onLogin_emptyForm_showsError() {
clickLoginButton()
onView(withId(R.id.login_error_text_view)).check(matches(isDisplayed()))
}
@Test
fun onLogin_invalidMobile_showsError() {
insertInMobileEditText(" 467856 ")
insertInPwdEditText("<PASSWORD>")
clickLoginButton()
onView(withId(R.id.login_mobile_edit_text)).check(matches(hasErrorText(`is`(MOB_ERROR_TEXT))))
}
@Test
fun onLogin_validData_showsNoError() {
Intents.init()
insertInMobileEditText("9966339966")
insertInPwdEditText("<PASSWORD>")
clickLoginButton()
intended(hasComponent(OtpActivity::class.java.name))
}
private fun insertInMobileEditText(phone: String) =
onView(withId(R.id.login_mobile_edit_text)).perform(
scrollTo(),
clearText(),
typeText(phone)
)
private fun insertInPwdEditText(pwd: String) =
onView(withId(R.id.login_password_edit_text)).perform(
scrollTo(),
clearText(),
typeText(pwd)
)
private fun clickRememberSwitch() =
onView(withId(R.id.login_rem_switch))
.perform(scrollTo(), click())
private fun clickForgotTextView() =
onView(withId(R.id.login_forgot_tv))
.perform(scrollTo(), click())
private fun clickLoginButton() =
onView(withId(R.id.login_login_btn))
.perform(scrollTo(), click())
private fun clickSignUpText() =
onView(withId(R.id.login_signup_text_view)).perform(
scrollTo(),
clickClickableSpan("Sign Up")
)
}<file_sep>/README.md
# Shopping Android App
An e-commerce android application written in Kotlin where users can sell and buy products.
## Overview
The application contains list of products such as shoes, slippers on which user can click to view itd details and then, add them to cart. User can like and dislike the product as well. Also, User can sell products, if he/she signed up as a Seller.
Some other features are as following:
- Login / Signup with OTP Verification.
- Recyclerview with variable span size to show products.
- Search Bar and filtering
- Product detail screen with image carousel and custom Radio Buttons.
- Add/Edit Product for Sellers
- See all orders placed.
- Increase/Decrease quantity of product in cart.
- Place Order.
- Modify status of order for Seller.
- Add/Edit Address
- Tested using Espresso. Written unit, instrumentation and UI tests.
## Some Screenshots
| Splash Screen | Application Home | Product Detail |
| :----------------------------------: | :---------------------------------------: | :----------------------------------:|
| ![](snapshots/shopping-launcher.png) | ![](snapshots/shopping-home-customer.png) | ![](snapshots/shopping-product.png) |
| Signup | Login | OTP Verification |
| :---------------------------------: | :-------------------------------: | :------------------------------:|
| ![](snapshots/shopping-sign-up.png) | ![](snapshots/shopping-login.png) | ![](snapshots/shopping-otp.png) |
| Shopping Cart | Address Selection | Payment Method | Order Success |
| :------------------------------: | :----------------------------------------: | :-------------------------------------:| :---------------------------------------: |
| ![](snapshots/shopping-cart.png) | ![](snapshots/shopping-select-address.png) | ![](snapshots/shopping-choose-pay.png) | ![](snapshots/shopping-order-success.png) |
| Add Product | All Orders | Order Detail | Sign Out |
| :-------------------------------------: | :--------------------------------: | :---------------------------------------:| :----------------------------------: |
| ![](snapshots/shopping-add-product.png) | ![](snapshots/shopping-orders.png) | ![](snapshots/shopping-order-detail.png) | ![](snapshots/shopping-sign-out.png) |
## Built With
- Kotlin
- Firebase
- Room
- Material
- Glide
---
<p align="center"> Made with :blue_heart: by <a href="https://github.com/i-vishi"><NAME></a></p><file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/FakeProductsRepository.kt
package com.vishalgaur.shoppingapp.data.source
import android.net.Uri
import androidx.core.net.toUri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import kotlinx.coroutines.runBlocking
import java.util.*
import kotlin.collections.LinkedHashMap
class FakeProductsRepository : ProductsRepoInterface {
var productsServiceData: LinkedHashMap<String, Product> = LinkedHashMap()
private val imagesStorage = mutableListOf<String>()
private val observableProducts = MutableLiveData<Result<List<Product>>>()
override suspend fun refreshProducts(): StoreDataStatus {
observableProducts.value = Success(productsServiceData.values.toList())
return StoreDataStatus.DONE
}
override fun observeProducts(): LiveData<Result<List<Product>>?> {
runBlocking { refreshProducts() }
return observableProducts
}
override fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?> {
runBlocking { refreshProducts() }
return Transformations.map(observableProducts) { products ->
when (products) {
is Result.Loading -> Result.Loading
is Error -> Error(products.exception)
is Success -> {
val pros = products.data.filter { it.owner == ownerId }
Success(pros)
}
}
}
}
override suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>> {
productsServiceData.values.let { pros ->
val res = pros.filter { it.owner == ownerId }
return Success(res)
}
}
override suspend fun getProductById(productId: String, forceUpdate: Boolean): Result<Product> {
productsServiceData[productId]?.let {
return Success(it)
}
return Error(Exception("Product Not Found!"))
}
override suspend fun insertProduct(newProduct: Product): Result<Boolean> {
productsServiceData[newProduct.productId] = newProduct
return Success(true)
}
override suspend fun insertImages(imgList: List<Uri>): List<String> {
val result = mutableListOf<String>()
imgList.forEach { uri ->
val uniId = UUID.randomUUID().toString()
val fileName = uniId + uri.lastPathSegment?.split("/")?.last()
val res = uri.toString() + fileName
imagesStorage.add(res)
result.add(res)
}
return result
}
override suspend fun updateProduct(product: Product): Result<Boolean> {
productsServiceData[product.productId] = product
return Success(true)
}
override suspend fun updateImages(newList: List<Uri>, oldList: List<String>): List<String> {
val urlList = mutableListOf<String>()
newList.forEach { uri ->
if (!oldList.contains(uri.toString())) {
val uniId = UUID.randomUUID().toString()
val fileName = uniId + uri.lastPathSegment?.split("/")?.last()
val res = uri.toString() + fileName
imagesStorage.add(res)
urlList.add(res)
} else {
urlList.add(uri.toString())
}
}
oldList.forEach { imgUrl ->
if (!newList.contains(imgUrl.toUri())) {
imagesStorage.remove(imgUrl)
}
}
return urlList
}
override suspend fun deleteProductById(productId: String): Result<Boolean> {
productsServiceData.remove(productId)
refreshProducts()
return Success(true)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/utils/ListTypeConverter.kt
package com.vishalgaur.shoppingapp.data.utils
import androidx.room.TypeConverter
class ListTypeConverter {
@TypeConverter
fun fromStringToStringList(value: String): List<String> {
return value.split(",").map { it }
}
@TypeConverter
fun fromStringListToString(value: List<String>): String {
return value.joinToString(separator = ",")
}
@TypeConverter
fun fromStringToIntegerList(value: String): List<Int> {
return value.split(",").map { it.toInt() }
}
@TypeConverter
fun fromIntegerListToString(value: List<Int>): String {
return value.joinToString(separator = ",")
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/RecyclerViewMatcherUtils.kt
package com.vishalgaur.shoppingapp
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.ViewAction
import androidx.test.espresso.ViewAssertion
import androidx.test.espresso.matcher.BoundedMatcher
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
fun atPosition(position: Int, itemMatcher: Matcher<View?>): Matcher<View?> {
return object : BoundedMatcher<View?, RecyclerView>(RecyclerView::class.java) {
override fun describeTo(description: Description) {
description.appendText("has item at position $position: ")
itemMatcher.describeTo(description)
}
override fun matchesSafely(view: RecyclerView): Boolean {
val viewHolder = view.findViewHolderForAdapterPosition(position)
?: // has no item on such position
return false
return itemMatcher.matches(viewHolder.itemView)
}
}
}
abstract class RecyclerViewItemAction: ViewAction {
override fun getConstraints(): Matcher<View>? {
return null
}
override fun getDescription(): String {
return "Action on a specific Button"
}
}
class RecyclerViewItemCountAssertion(private val expectedCount: Int) : ViewAssertion {
override fun check(view: View, noViewFoundException: NoMatchingViewException?) {
if (noViewFoundException != null) {
throw noViewFoundException
}
val recyclerView = view as RecyclerView
val adapter = recyclerView.adapter
assertThat(adapter!!.itemCount, `is`(expectedCount))
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/FakeAuthRepository.kt
package com.vishalgaur.shoppingapp.data.source
import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.utils.EmailMobileData
import com.vishalgaur.shoppingapp.data.utils.SignUpErrors
import com.vishalgaur.shoppingapp.data.utils.UserType
class FakeAuthRepository(private val sessionManager: ShoppingAppSessionManager) :
AuthRepoInterface {
private var emailMobileData = EmailMobileData()
private var uData: UserData? = null
override suspend fun refreshData() {
// no implementation
}
override suspend fun signUp(userData: UserData) {
uData = userData
sessionManager.createLoginSession(
userData.userId,
userData.name,
userData.mobile,
false,
userData.userType == UserType.SELLER.name
)
}
override fun login(userData: UserData, rememberMe: Boolean) {
uData = userData
sessionManager.createLoginSession(
userData.userId,
userData.name,
userData.mobile,
rememberMe,
userData.userType == UserType.SELLER.name
)
}
override suspend fun checkEmailAndMobile(
email: String,
mobile: String,
context: Context
): SignUpErrors {
// no implementation
return SignUpErrors.NONE
}
override suspend fun checkLogin(mobile: String, password: String): UserData? {
uData?.let {
if (it.mobile == mobile && it.password == <PASSWORD>) {
return it
}
}
return null
}
override suspend fun signOut() {
uData = null
sessionManager.logoutFromSession()
}
override suspend fun hardRefreshUserData() {
// no implementation
}
override suspend fun insertProductToLikes(productId: String, userId: String): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val likes = it.likes.toMutableList()
likes.add(productId)
it.likes = likes
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun removeProductFromLikes(
productId: String,
userId: String
): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val likes = it.likes.toMutableList()
likes.remove(productId)
it.likes = likes
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun insertAddress(
newAddress: UserData.Address,
userId: String
): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val addresses = it.addresses.toMutableList()
addresses.add(newAddress)
it.addresses = addresses
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun updateAddress(
newAddress: UserData.Address,
userId: String
): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val addresses = it.addresses.toMutableList()
addresses.add(newAddress)
val pos =
it.addresses.indexOfFirst { address -> address.addressId == newAddress.addressId }
if (pos >= 0) {
addresses[pos] = newAddress
}
it.addresses = addresses
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun deleteAddressById(addressId: String, userId: String): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val addresses = it.addresses.toMutableList()
val pos = it.addresses.indexOfFirst { address -> address.addressId == addressId }
if (pos >= 0) {
addresses.removeAt(pos)
}
it.addresses = addresses
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun insertCartItemByUserId(
cartItem: UserData.CartItem,
userId: String
): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val cart = it.cart.toMutableList()
cart.add(cartItem)
it.cart = cart
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun updateCartItemByUserId(
cartItem: UserData.CartItem,
userId: String
): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val cart = it.cart.toMutableList()
val pos = it.cart.indexOfFirst { item -> item.itemId == cartItem.itemId }
if (pos >= 0) {
cart[pos] = cartItem
}
it.cart = cart
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun deleteCartItemByUserId(itemId: String, userId: String): Result<Boolean> {
uData?.let {
if (it.userId == userId) {
val cart = it.cart.toMutableList()
val pos = it.cart.indexOfFirst { item -> item.itemId == itemId }
if (pos >= 0) {
cart.removeAt(pos)
}
it.cart = cart
return Result.Success(true)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?> {
uData?.let {
if (it.userId == userId) {
return Result.Success(it.addresses)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun getLikesByUserId(userId: String): Result<List<String>?> {
uData?.let {
if (it.userId == userId) {
return Result.Success(it.likes)
}
}
return Result.Error(Exception("User Not Found"))
}
override suspend fun getUserData(userId: String): Result<UserData?> {
uData?.let {
if (it.userId == userId) {
return Result.Success(it)
}
}
return Result.Error(Exception("User Not Found"))
}
override fun getFirebaseAuth(): FirebaseAuth {
return Firebase.auth
}
override fun signInWithPhoneAuthCredential(
credential: PhoneAuthCredential,
isUserLoggedIn: MutableLiveData<Boolean>,
context: Context
) {
// no implementation
}
override fun isRememberMeOn(): Boolean {
// no implementation
return true
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/loginSignup/LoginFragment.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import android.text.SpannableString
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.os.bundleOf
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.MOB_ERROR_TEXT
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.LogInErrors
import com.vishalgaur.shoppingapp.databinding.FragmentLoginBinding
import com.vishalgaur.shoppingapp.ui.LoginViewErrors
class LoginFragment : LoginSignupBaseFragment<FragmentLoginBinding>() {
override fun setViewBinding(): FragmentLoginBinding {
return FragmentLoginBinding.inflate(layoutInflater)
}
override fun observeView() {
super.observeView()
viewModel.errorStatusLoginFragment.observe(viewLifecycleOwner) { err ->
modifyErrors(err)
}
viewModel.loginErrorStatus.observe(viewLifecycleOwner) { err ->
when (err) {
LogInErrors.LERR -> setErrorText(getString(R.string.login_error_text))
else -> binding.loginErrorTextView.visibility = View.GONE
}
}
}
override fun setUpViews() {
super.setUpViews()
binding.loginErrorTextView.visibility = View.GONE
binding.loginMobileEditText.onFocusChangeListener = focusChangeListener
binding.loginPasswordEditText.onFocusChangeListener = focusChangeListener
binding.loginLoginBtn.setOnClickListener(object : OnClickListener {
override fun onClick(v: View?) {
onLogin()
if (viewModel.errorStatusLoginFragment.value == LoginViewErrors.NONE) {
viewModel.loginErrorStatus.observe(viewLifecycleOwner) {
if (it == LogInErrors.NONE) {
val isRemOn = binding.loginRemSwitch.isChecked
val bundle = bundleOf(
"uData" to viewModel.userData.value,
"loginRememberMe" to isRemOn
)
launchOtpActivity(getString(R.string.login_fragment_label), bundle)
}
}
}
}
})
setUpClickableSignUpText()
}
private fun modifyErrors(err: LoginViewErrors) {
when (err) {
LoginViewErrors.NONE -> setEditTextErrors()
LoginViewErrors.ERR_EMPTY -> setErrorText("Fill all details")
LoginViewErrors.ERR_MOBILE -> setEditTextErrors(MOB_ERROR_TEXT)
}
}
private fun setErrorText(errText: String?) {
binding.loginErrorTextView.visibility = View.VISIBLE
if (errText != null) {
binding.loginErrorTextView.text = errText
}
}
private fun setEditTextErrors(mobError: String? = null) {
binding.loginErrorTextView.visibility = View.GONE
binding.loginMobileEditText.error = mobError
}
private fun setUpClickableSignUpText() {
val signUpText = getString(R.string.login_signup_text)
val ss = SpannableString(signUpText)
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
findNavController().navigateUp()
}
}
ss.setSpan(clickableSpan, 10, 17, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
binding.loginSignupTextView.apply {
text = ss
movementMethod = LinkMovementMethod.getInstance()
}
}
private fun onLogin() {
val mob = binding.loginMobileEditText.text.toString()
val pwd = binding.loginPasswordEditText.text.toString()
viewModel.loginSubmitData(mob, pwd)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/SelectPaymentFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.databinding.FragmentSelectPaymentBinding
import com.vishalgaur.shoppingapp.viewModels.OrderViewModel
private const val TAG = "SelectMethodFragment"
class SelectPaymentFragment : Fragment() {
private lateinit var binding: FragmentSelectPaymentBinding
private var methodsAdapter = PayByAdapter(getPaymentMethods())
private val orderViewModel: OrderViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSelectPaymentBinding.inflate(layoutInflater)
setViews()
return binding.root
}
private fun setViews() {
binding.payByAppBar.topAppBar.title = getString(R.string.pay_by_title)
binding.payByAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.payByErrorTextView.visibility = View.GONE
binding.payByPaymentsRecyclerView.adapter = methodsAdapter
binding.payByNextBtn.text =
getString(R.string.pay_by_next_btn_text, orderViewModel.getItemsPriceTotal().toString())
binding.payByNextBtn.setOnClickListener {
navigateToOrderSuccess(methodsAdapter.lastCheckedMethod)
}
}
private fun navigateToOrderSuccess(method: String?) {
if (method != null) {
orderViewModel.setSelectedPaymentMethod(method)
Log.d(TAG, "navigate to order Success")
binding.payByErrorTextView.visibility = View.GONE
orderViewModel.finalizeOrder()
// save order
// wait for save add observer
// if success, navigate
findNavController().navigate(R.id.action_selectPaymentFragment_to_orderSuccessFragment)
} else {
Log.d(TAG, "Error: Select a payment method!")
binding.payByErrorTextView.visibility = View.VISIBLE
}
}
private fun getPaymentMethods(): List<String> {
return listOf("UPI", "Debit Card", "Cash On Delivery")
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/OrdersFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentOrdersBinding
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
private const val TAG = "OrdersFragment"
class OrdersFragment : Fragment() {
private lateinit var binding: FragmentOrdersBinding
private lateinit var ordersAdapter: OrdersAdapter
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentOrdersBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getAllOrders()
}
private fun setViews() {
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.ordersAppBar.topAppBar.title = getString(R.string.orders_fragment_title)
binding.ordersAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.ordersEmptyTextView.visibility = View.GONE
if (context != null) {
ordersAdapter = OrdersAdapter(emptyList(), requireContext())
ordersAdapter.onClickListener = object : OrdersAdapter.OnClickListener {
override fun onCardClick(orderId: String) {
Log.d(TAG, "onOrderSummaryClick: Getting order details")
findNavController().navigate(
R.id.action_ordersFragment_to_orderDetailsFragment,
bundleOf("orderId" to orderId)
)
}
}
binding.orderAllOrdersRecyclerView.adapter = ordersAdapter
}
}
private fun setObservers() {
viewModel.storeDataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.orderAllOrdersRecyclerView.visibility = View.GONE
binding.ordersEmptyTextView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
else -> {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
}
}
if (status != null && status != StoreDataStatus.LOADING) {
viewModel.userOrders.observe(viewLifecycleOwner) { orders ->
if (orders.isNotEmpty()) {
ordersAdapter.data = orders.sortedByDescending { it.orderDate }
binding.orderAllOrdersRecyclerView.adapter?.notifyDataSetChanged()
binding.orderAllOrdersRecyclerView.visibility = View.VISIBLE
} else if (orders.isEmpty()) {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.ordersEmptyTextView.visibility = View.VISIBLE
}
}
}
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/AddEditProductViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.net.Uri
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.vishalgaur.shoppingapp.ERR_UPLOAD
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.utils.AddProductErrors
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.getProductId
import com.vishalgaur.shoppingapp.ui.AddProductViewErrors
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
private const val TAG = "AddEditViewModel"
class AddEditProductViewModel(application: Application) : AndroidViewModel(application) {
private val productsRepository =
(application.applicationContext as ShoppingApplication).productsRepository
private val sessionManager = ShoppingAppSessionManager(application.applicationContext)
private val currentUser = sessionManager.getUserIdFromSession()
private val _selectedCategory = MutableLiveData<String>()
val selectedCategory: LiveData<String> get() = _selectedCategory
private val _productId = MutableLiveData<String>()
val productId: LiveData<String> get() = _productId
private val _isEdit = MutableLiveData<Boolean>()
val isEdit: LiveData<Boolean> get() = _isEdit
private val _errorStatus = MutableLiveData<AddProductViewErrors>()
val errorStatus: LiveData<AddProductViewErrors> get() = _errorStatus
private val _dataStatus = MutableLiveData<StoreDataStatus>()
val dataStatus: LiveData<StoreDataStatus> get() = _dataStatus
private val _addProductErrors = MutableLiveData<AddProductErrors?>()
val addProductErrors: LiveData<AddProductErrors?> get() = _addProductErrors
private val _productData = MutableLiveData<Product>()
val productData: LiveData<Product> get() = _productData
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
val newProductData = MutableLiveData<Product>()
init {
_errorStatus.value = AddProductViewErrors.NONE
}
fun setIsEdit(state: Boolean) {
_isEdit.value = state
}
fun setCategory(catName: String) {
_selectedCategory.value = catName
}
fun setProductData(productId: String) {
_productId.value = productId
viewModelScope.launch {
Log.d(TAG, "onLoad: Getting product Data")
_dataStatus.value = StoreDataStatus.LOADING
val res = async { productsRepository.getProductById(productId) }
val proRes = res.await()
if (proRes is Success) {
val proData = proRes.data
_productData.value = proData
_selectedCategory.value = _productData.value!!.category
Log.d(TAG, "onLoad: Successfully retrieved product data")
_dataStatus.value = StoreDataStatus.DONE
} else if (proRes is Error) {
_dataStatus.value = StoreDataStatus.ERROR
Log.d(TAG, "onLoad: Error getting product data")
_productData.value = Product()
}
}
}
fun submitProduct(
name: String,
price: Double?,
mrp: Double?,
desc: String,
sizes: List<Int>,
colors: List<String>,
imgList: List<Uri>,
) {
if (name.isBlank() || price == null || mrp == null || desc.isBlank() || sizes.isNullOrEmpty() || colors.isNullOrEmpty() || imgList.isNullOrEmpty()) {
_errorStatus.value = AddProductViewErrors.EMPTY
} else {
if (price == 0.0 || mrp == 0.0) {
_errorStatus.value = AddProductViewErrors.ERR_PRICE_0
} else {
_errorStatus.value = AddProductViewErrors.NONE
val proId = if (_isEdit.value == true) _productId.value!! else
getProductId(currentUser!!, selectedCategory.value!!)
val newProduct =
Product(
proId,
name.trim(),
currentUser!!,
desc.trim(),
_selectedCategory.value!!,
price,
mrp,
sizes,
colors,
emptyList(),
0.0
)
newProductData.value = newProduct
Log.d(TAG, "pro = $newProduct")
if (_isEdit.value == true) {
updateProduct(imgList)
} else {
insertProduct(imgList)
}
}
}
}
private fun updateProduct(imgList: List<Uri>) {
viewModelScope.launch {
if (newProductData.value != null && _productData.value != null) {
_addProductErrors.value = AddProductErrors.ADDING
val resImg =
async { productsRepository.updateImages(imgList, _productData.value!!.images) }
val imagesPaths = resImg.await()
newProductData.value?.images = imagesPaths
if (newProductData.value?.images?.isNotEmpty() == true) {
if (imagesPaths[0] == ERR_UPLOAD) {
Log.d(TAG, "error uploading images")
_addProductErrors.value = AddProductErrors.ERR_ADD_IMG
} else {
val updateRes =
async { productsRepository.updateProduct(newProductData.value!!) }
val res = updateRes.await()
if (res is Success) {
Log.d(TAG, "onUpdate: Success")
_addProductErrors.value = AddProductErrors.NONE
} else {
Log.d(TAG, "onUpdate: Some error occurred!")
_addProductErrors.value = AddProductErrors.ERR_ADD
if (res is Error)
Log.d(TAG, "onUpdate: Error, ${res.exception}")
}
}
} else {
Log.d(TAG, "Product images empty, Cannot Add Product")
}
} else {
Log.d(TAG, "Product is Null, Cannot Add Product")
}
}
}
private fun insertProduct(imgList: List<Uri>) {
viewModelScope.launch {
if (newProductData.value != null) {
_addProductErrors.value = AddProductErrors.ADDING
val resImg = async { productsRepository.insertImages(imgList) }
val imagesPaths = resImg.await()
newProductData.value?.images = imagesPaths
if (newProductData.value?.images?.isNotEmpty() == true) {
if (imagesPaths[0] == ERR_UPLOAD) {
Log.d(TAG, "error uploading images")
_addProductErrors.value = AddProductErrors.ERR_ADD_IMG
} else {
val deferredRes = async {
productsRepository.insertProduct(newProductData.value!!)
}
val res = deferredRes.await()
if (res is Success) {
Log.d(TAG, "onInsertProduct: Success")
_addProductErrors.value = AddProductErrors.NONE
} else {
_addProductErrors.value = AddProductErrors.ERR_ADD
if (res is Error)
Log.d(TAG, "onInsertProduct: Error Occurred, ${res.exception}")
}
}
} else {
Log.d(TAG, "Product images empty, Cannot Add Product")
}
} else {
Log.d(TAG, "Product is Null, Cannot Add Product")
}
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/loginSignup/OtpActivity.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import android.app.Application
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.google.android.material.snackbar.Snackbar
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.databinding.ActivityOtpBinding
import com.vishalgaur.shoppingapp.ui.OTPStatus
import com.vishalgaur.shoppingapp.ui.launchHome
import com.vishalgaur.shoppingapp.viewModels.OtpViewModel
class OtpActivity : AppCompatActivity() {
private lateinit var binding: ActivityOtpBinding
private lateinit var viewModel: OtpViewModel
private lateinit var fromWhere: String
class OtpViewModelFactory(
private val application: Application, private val uData: UserData
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(OtpViewModel::class.java)) {
return OtpViewModel(application, uData) as T
}
throw IllegalArgumentException("Unknown ViewModel Class")
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityOtpBinding.inflate(layoutInflater)
val uData: UserData? = intent.getParcelableExtra("uData")
fromWhere = intent.getStringExtra("from").toString()
if (uData != null) {
val viewModelFactory = OtpViewModelFactory(application, uData)
viewModel =
ViewModelProvider(this, viewModelFactory).get(OtpViewModel::class.java)
viewModel.verifyPhoneOTPStart(uData.mobile, this)
}
setViews()
setObservers()
setContentView(binding.root)
}
private fun setObservers() {
viewModel.otpStatus.observe(this) {
when (it) {
OTPStatus.WRONG -> binding.otpVerifyError.visibility = View.VISIBLE
else -> binding.otpVerifyError.visibility = View.GONE
}
}
viewModel.isUserLoggedIn.observe(this) {
if (it == true) {
if (fromWhere == getString(R.string.signup_fragment_label)) {
viewModel.signUp()
} else {
val rememberMe = intent.getBooleanExtra("loginRememberMe", false)
viewModel.login(rememberMe)
}
launchHome(this)
finish()
}
}
viewModel.isOTPSent.observe(this) {
if(it == true) {
binding.loaderLayout.loaderCard.visibility = View.GONE
val contextView = binding.loaderLayout.loaderCard
Snackbar.make(contextView, R.string.otp_sent_msg, Snackbar.LENGTH_SHORT).show()
}
}
}
private fun setViews() {
binding.otpVerifyError.visibility = View.GONE
binding.loaderLayout.loaderCard.visibility = View.VISIBLE
binding.loaderLayout.loadingMessage.text = getString(R.string.sending_otp_msg)
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.otpVerifyBtn.setOnClickListener {
onVerify()
}
}
private fun onVerify() {
val otp = binding.otpOtpEditText.text.toString()
viewModel.verifyOTP(otp)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/UiUtils.kt
package com.vishalgaur.shoppingapp.ui
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.getISOCountriesMap
import com.vishalgaur.shoppingapp.ui.home.MainActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.max
enum class SignUpViewErrors { NONE, ERR_EMAIL, ERR_MOBILE, ERR_EMAIL_MOBILE, ERR_EMPTY, ERR_NOT_ACC, ERR_PWD12NS }
enum class LoginViewErrors { NONE, ERR_EMPTY, ERR_MOBILE }
enum class OTPStatus { NONE, CORRECT, WRONG }
enum class AddProductViewErrors { NONE, EMPTY, ERR_PRICE_0 }
enum class AddAddressViewErrors { EMPTY, ERR_FNAME_EMPTY, ERR_LNAME_EMPTY, ERR_STR1_EMPTY, ERR_CITY_EMPTY, ERR_STATE_EMPTY, ERR_ZIP_EMPTY, ERR_ZIP_INVALID, ERR_PHONE_INVALID, ERR_PHONE_EMPTY }
enum class AddItemErrors { ERROR_SIZE, ERROR_COLOR }
class MyOnFocusChangeListener : View.OnFocusChangeListener {
override fun onFocusChange(v: View?, hasFocus: Boolean) {
if (v != null) {
val inputManager =
v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (!hasFocus) {
inputManager.hideSoftInputFromWindow(v.windowToken, 0)
} else {
inputManager.toggleSoftInputFromWindow(v.windowToken, 0, 0)
}
}
}
}
fun <T> throttleLatest(
intervalMs: Long = 300L,
coroutineScope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var throttleJob: Job? = null
var latestParam: T
return { param: T ->
latestParam = param
if (throttleJob?.isCompleted != false) {
throttleJob = coroutineScope.launch {
delay(intervalMs)
latestParam.let(destinationFunction)
}
}
}
}
fun <T> debounce(
waitMs: Long = 300L,
coroutineScope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
debounceJob?.cancel()
debounceJob = coroutineScope.launch {
delay(waitMs)
destinationFunction(param)
}
}
}
class DotsIndicatorDecoration(
private val radius: Float,
private val indicatorItemPadding: Float,
private val indicatorHeight: Int,
@ColorInt private val colorInactive: Int,
@ColorInt private val colorActive: Int
) : RecyclerView.ItemDecoration() {
private val inactivePaint = Paint()
private val activePaint = Paint()
init {
val width = Resources.getSystem().displayMetrics.density * 1
inactivePaint.apply {
strokeCap = Paint.Cap.ROUND
strokeWidth = width
style = Paint.Style.STROKE
isAntiAlias = true
color = colorInactive
}
activePaint.apply {
strokeCap = Paint.Cap.ROUND
strokeWidth = width
style = Paint.Style.FILL_AND_STROKE
isAntiAlias = true
color = colorActive
}
}
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
val adapter = parent.adapter ?: return
val itemCount = adapter.itemCount
val totalLength: Float = (radius * 2 * itemCount)
val padBWItems = max(0, itemCount - 1) * indicatorItemPadding
val indicatorTotalWidth = totalLength + padBWItems
val indicatorStartX = (parent.width - indicatorTotalWidth) / 2F
val indicatorPosY = parent.height - indicatorHeight / 2F
drawInactiveDots(c, indicatorStartX, indicatorPosY, itemCount)
val activePos: Int =
(parent.layoutManager as LinearLayoutManager).findFirstVisibleItemPosition()
if (activePos == RecyclerView.NO_POSITION) {
return
}
val activeChild =
(parent.layoutManager as LinearLayoutManager).findViewByPosition(activePos)
?: return
drawActiveDot(c, indicatorStartX, indicatorPosY, activePos)
}
private fun drawInactiveDots(
c: Canvas,
indicatorStartX: Float,
indicatorPosY: Float,
itemCount: Int
) {
val w = radius * 2 + indicatorItemPadding
var st = indicatorStartX + radius
for (i in 1..itemCount) {
c.drawCircle(st, indicatorPosY, radius, inactivePaint)
st += w
}
}
private fun drawActiveDot(
c: Canvas,
indicatorStartX: Float,
indicatorPosY: Float,
highlightPos: Int
) {
val w = radius * 2 + indicatorItemPadding
val highStart = indicatorStartX + radius + w * highlightPos
c.drawCircle(highStart, indicatorPosY, radius, activePaint)
}
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
super.getItemOffsets(outRect, view, parent, state)
outRect.bottom = indicatorHeight
}
}
internal fun launchHome(context: Context) {
val homeIntent = Intent(context, MainActivity::class.java)
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(homeIntent)
}
internal fun getCompleteAddress(address: UserData.Address): String {
return if (address.streetAddress2.isBlank()) {
"${address.streetAddress}, ${address.city}, ${address.state} - ${address.zipCode}, ${getISOCountriesMap()[address.countryISOCode]}"
} else {
"${address.streetAddress}, ${address.streetAddress2}, ${address.city}, ${address.state} - ${address.zipCode}, ${getISOCountriesMap()[address.countryISOCode]}"
}
}
internal fun disableClickOnWindow(activity: Activity) {
activity.window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
)
}
internal fun enableClickOnWindow(activity: Activity) {
activity.window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/Product.kt
package com.vishalgaur.shoppingapp.data
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Parcelize
@Entity(tableName = "products")
data class Product @JvmOverloads constructor(
@PrimaryKey
var productId: String = "",
var name: String = "",
var owner: String = "",
var description: String = "",
var category: String = "",
var price: Double = 0.0,
var mrp: Double = 0.0,
var availableSizes: List<Int> = ArrayList(),
var availableColors: List<String> = ArrayList(),
var images: List<String> = ArrayList(),
var rating: Double = 0.0
) : Parcelable {
fun toHashMap(): HashMap<String, Any> {
return hashMapOf(
"productId" to productId,
"name" to name,
"owner" to owner,
"description" to description,
"category" to category,
"price" to price,
"mrp" to mrp,
"availableSizes" to availableSizes,
"availableColors" to availableColors,
"images" to images,
"rating" to rating
)
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/viewModels/HomeViewModelTest.kt
package com.vishalgaur.shoppingapp.viewModels
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.ServiceLocator
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.source.FakeAuthRepository
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.getOrAwaitValue
import org.hamcrest.Matchers.`is`
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class HomeViewModelTest {
private lateinit var homeViewModel: HomeViewModel
private lateinit var authRepository: AuthRepoInterface
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
val sessionManager = ShoppingAppSessionManager(ApplicationProvider.getApplicationContext())
authRepository = FakeAuthRepository(sessionManager)
ServiceLocator.authRepository = authRepository
homeViewModel = HomeViewModel(ApplicationProvider.getApplicationContext())
}
@After
fun cleanUp() {
ServiceLocator.resetRepository()
}
@Test
fun setDataLoaded_setsValue() {
homeViewModel.setDataLoaded()
val result = homeViewModel.storeDataStatus.getOrAwaitValue()
assertThat(result, `is`(StoreDataStatus.DONE))
}
@Test
fun filterProducts_All() {
homeViewModel.filterProducts("All")
val result = homeViewModel.filterCategory.getOrAwaitValue()
assertThat(result, `is`("All"))
}
@Test
fun filterProducts_Shoes() {
homeViewModel.filterProducts("Shoes")
val result = homeViewModel.filterCategory.getOrAwaitValue()
assertThat(result, `is`("Shoes"))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/SelectAddressFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentSelectAddressBinding
import com.vishalgaur.shoppingapp.viewModels.OrderViewModel
private const val TAG = "ShipToFragment"
class SelectAddressFragment : Fragment() {
private lateinit var binding: FragmentSelectAddressBinding
private val orderViewModel: OrderViewModel by activityViewModels()
private lateinit var addressAdapter: AddressAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentSelectAddressBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
orderViewModel.getUserAddresses()
}
private fun setObservers() {
orderViewModel.dataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.addressEmptyTextView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
else -> {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
}
}
if(status != null && status != StoreDataStatus.LOADING) {
orderViewModel.userAddresses.observe(viewLifecycleOwner) { addressList ->
if (addressList.isNotEmpty()) {
addressAdapter.data = addressList
binding.shipToAddressesRecyclerView.adapter = addressAdapter
binding.shipToAddressesRecyclerView.adapter?.notifyDataSetChanged()
} else if (addressList.isEmpty()) {
binding.shipToAddressesRecyclerView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.addressEmptyTextView.visibility = View.VISIBLE
}
}
}
}
}
private fun setViews() {
binding.shipToAppBar.topAppBar.title = getString(R.string.ship_to_title)
binding.shipToAppBar.topAppBar.inflateMenu(R.menu.menu_with_add_only)
binding.shipToAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.shipToErrorTextView.visibility = View.GONE
binding.addressEmptyTextView.visibility = View.GONE
binding.shipToAppBar.topAppBar.setOnMenuItemClickListener { menuItem ->
if (menuItem.itemId == R.id.add_item) {
navigateToAddEditAddress(false)
true
} else {
false
}
}
if (context != null) {
addressAdapter = AddressAdapter(
requireContext(),
orderViewModel.userAddresses.value ?: emptyList(),
true
)
addressAdapter.onClickListener = object : AddressAdapter.OnClickListener {
override fun onEditClick(addressId: String) {
Log.d(TAG, "onEditAddress: initiated")
navigateToAddEditAddress(true, addressId)
}
override fun onDeleteClick(addressId: String) {
Log.d(TAG, "onDeleteAddress: initiated")
showDeleteDialog(addressId)
}
}
binding.shipToAddressesRecyclerView.adapter = addressAdapter
}
binding.shipToNextBtn.setOnClickListener {
navigateToPaymentFragment(addressAdapter.lastCheckedAddress)
}
}
private fun showDeleteDialog(addressId: String) {
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.delete_dialog_title_text))
.setMessage(getString(R.string.delete_address_message_text))
.setNeutralButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.delete_dialog_delete_btn_text)) { dialog, _ ->
orderViewModel.deleteAddress(addressId)
dialog.cancel()
}
.show()
}
}
private fun navigateToPaymentFragment(addressId: String?) {
if (addressId != null) {
orderViewModel.setSelectedAddress(addressId)
Log.d(TAG, "navigate to Payment")
binding.shipToErrorTextView.visibility = View.GONE
findNavController().navigate(R.id.action_selectAddressFragment_to_selectPaymentFragment)
} else {
Log.d(TAG, "error = select one address")
binding.shipToErrorTextView.visibility = View.VISIBLE
}
}
private fun navigateToAddEditAddress(isEdit: Boolean, addressId: String? = null) {
findNavController().navigate(
R.id.action_selectAddressFragment_to_addEditAddressFragment,
bundleOf("isEdit" to isEdit, "addressId" to addressId)
)
}
}<file_sep>/app/src/test/java/com/vishalgaur/shoppingapp/UtilsTest.kt
package com.vishalgaur.shoppingapp
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertEquals
import org.junit.Test
class UtilsTest {
@Test
fun checkEmail_empty_returnsFalse() {
val email = ""
val result = isEmailValid(email)
assertEquals(result, false)
}
@Test
fun checkEmail_invalid_returnsFalse() {
val email1 = "vishalgaur"
val email2 = "vishalgaur.com"
val email3 = "<EMAIL>"
val result1 = isEmailValid(email1)
val result2 = isEmailValid(email2)
val result3 = isEmailValid(email3)
assertEquals(result1, false)
assertEquals(result2, false)
assertEquals(result3, false)
}
@Test
fun checkEmail_valid_returnsTrue() {
val email1 = " <EMAIL>"
val email2 = "<EMAIL> "
val email3 = "<EMAIL>"
val result1 = isEmailValid(email1)
val result2 = isEmailValid(email2)
val result3 = isEmailValid(email3)
assertEquals(result1, true)
assertEquals(result2, true)
assertEquals(result3, true)
}
@Test
fun checkPhone_empty_returnsFalse() {
val phone = ""
val result = isPhoneValid(phone)
assertEquals(result, false)
}
@Test
fun checkPhone_invalid_returnsFalse() {
val phone1 = "1968743574694865"
val phone2 = " 1111 "
val phone3 = "2454678910"
val result1 = isPhoneValid(phone1)
val result2 = isPhoneValid(phone2)
val result3 = isPhoneValid(phone3)
assertEquals(result1, false)
assertEquals(result2, false)
assertEquals(result3, false)
}
@Test
fun checkPhone_valid_returnsTrue() {
val phone1 = "9876543210"
val phone2 = " 6985741526"
val phone3 = "8989895858 "
val result1 = isPhoneValid(phone1)
val result2 = isPhoneValid(phone2)
val result3 = isPhoneValid(phone3)
assertEquals(result1, true)
assertEquals(result2, true)
assertEquals(result3, true)
}
@Test
fun getRandomString_hasExpectedLength() {
val result1 = getRandomString(10, "odweuih", 10)
val result2 = getRandomString(10, "", 5)
assertThat(result1.length, `is`(27))
assertThat(result2.length, `is`(15))
}
@Test
fun getProductId_hasExpectedSubStrings() {
val result = getProductId("soewifnc9we48yf0", "shoes")
val subs = result.split("-")
assert(subs.size >= 3)
}
@Test
fun getOfferPercentage_zeroZero_returnsZero() {
val result = getOfferPercentage(0.0, 0.0)
assertThat(result, `is`(0))
}
@Test
fun getOfferPercentage_highLow_returnsZero() {
val result = getOfferPercentage(90.0, 100.0)
assertThat(result, `is`(0))
}
@Test
fun getOfferPercentage_lowHigh_returnsOfferInt() {
val result1 = getOfferPercentage(100.0, 90.5)
val result2 = getOfferPercentage(100.0, 90.75)
val result3 = getOfferPercentage(100.0, 90.25)
assertThat(result1, `is`(10))
assertThat(result2, `is`(9))
assertThat(result3, `is`(10))
}
@Test
fun getOfferPercentage_equal_returnsZero() {
val result = getOfferPercentage(90.5, 90.5)
assertThat(result, `is`(0))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/remote/ProductsRemoteDataSource.kt
package com.vishalgaur.shoppingapp.data.source.remote
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.ktx.storage
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.source.ProductDataSource
import kotlinx.coroutines.tasks.await
class ProductsRemoteDataSource : ProductDataSource {
private val firebaseDb: FirebaseFirestore = Firebase.firestore
private val firebaseStorage: FirebaseStorage = Firebase.storage
private val observableProducts = MutableLiveData<Result<List<Product>>?>()
private fun storageRef() = firebaseStorage.reference
private fun productsCollectionRef() = firebaseDb.collection(PRODUCT_COLLECTION)
override suspend fun refreshProducts() {
observableProducts.value = getAllProducts()
}
override fun observeProducts(): LiveData<Result<List<Product>>?> {
return observableProducts
}
override suspend fun getAllProducts(): Result<List<Product>> {
val resRef = productsCollectionRef().get().await()
return if (!resRef.isEmpty) {
Success(resRef.toObjects(Product::class.java))
} else {
Error(Exception("Error getting Products!"))
}
}
override suspend fun insertProduct(newProduct: Product) {
productsCollectionRef().add(newProduct.toHashMap()).await()
}
override suspend fun updateProduct(proData: Product) {
val resRef =
productsCollectionRef().whereEqualTo(PRODUCT_ID_FIELD, proData.productId).get().await()
if (!resRef.isEmpty) {
val docId = resRef.documents[0].id
productsCollectionRef().document(docId).set(proData.toHashMap()).await()
} else {
Log.d(TAG, "onUpdateProduct: product with id: $proData.productId not found!")
}
}
override suspend fun getProductById(productId: String): Result<Product> {
val resRef = productsCollectionRef().whereEqualTo(PRODUCT_ID_FIELD, productId).get().await()
return if (!resRef.isEmpty) {
Success(resRef.toObjects(Product::class.java)[0])
} else {
Error(Exception("Product with id: $productId Not Found!"))
}
}
override suspend fun deleteProduct(productId: String) {
Log.d(TAG, "onDeleteProduct: delete product with Id: $productId initiated")
val resRef = productsCollectionRef().whereEqualTo(PRODUCT_ID_FIELD, productId).get().await()
if (!resRef.isEmpty) {
val product = resRef.documents[0].toObject(Product::class.java)
val imgUrls = product?.images
//deleting images first
imgUrls?.forEach { imgUrl ->
deleteImage(imgUrl)
}
//deleting doc containing product
val docId = resRef.documents[0].id
productsCollectionRef().document(docId).delete().addOnSuccessListener {
Log.d(TAG, "onDelete: DocumentSnapshot successfully deleted!")
}.addOnFailureListener { e ->
Log.w(TAG, "onDelete: Error deleting document", e)
}
} else {
Log.d(TAG, "onDeleteProduct: product with id: $productId not found!")
}
}
override suspend fun uploadImage(uri: Uri, fileName: String): Uri? {
val imgRef = storageRef().child("$SHOES_STORAGE_PATH/$fileName")
val uploadTask = imgRef.putFile(uri)
val uriRef = uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let { throw it }
}
imgRef.downloadUrl
}
return uriRef.await()
}
override fun deleteImage(imgUrl: String) {
val ref = firebaseStorage.getReferenceFromUrl(imgUrl)
ref.delete().addOnSuccessListener {
Log.d(TAG, "onDelete: image deleted successfully!")
}.addOnFailureListener { e ->
Log.d(TAG, "onDelete: Error deleting image, error: $e")
}
}
override fun revertUpload(fileName: String) {
val imgRef = storageRef().child("${SHOES_STORAGE_PATH}/$fileName")
imgRef.delete().addOnSuccessListener {
Log.d(TAG, "onRevert: File with name: $fileName deleted successfully!")
}.addOnFailureListener { e ->
Log.d(TAG, "onRevert: Error deleting file with name = $fileName, error: $e")
}
}
companion object {
private const val PRODUCT_COLLECTION = "products"
private const val PRODUCT_ID_FIELD = "productId"
private const val SHOES_STORAGE_PATH = "Shoes"
private const val TAG = "ProductsRemoteSource"
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/repository/AuthRepositoryTest.kt
package com.vishalgaur.shoppingapp.data.source.repository
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.google.firebase.FirebaseApp
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.FakeUserDataSource
import com.vishalgaur.shoppingapp.data.utils.SignUpErrors
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.nullValue
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class AuthRepositoryTest {
private val userSeller = UserData(
"weoifhwenf29385",
"Seller Name",
"+919999990000",
"<EMAIL>",
"12345",
emptyList(),
emptyList(),
emptyList(),
"SELLER",
)
private val userCustomer = UserData(
"dwoeihwjklvn48329752",
"<NAME>",
"+919090909090",
"<EMAIL>",
"12345",
emptyList(),
emptyList(),
emptyList(),
"CUSTOMER",
)
private lateinit var context: Context
private lateinit var userLocalDataSource: FakeUserDataSource
private lateinit var authRemoteDataSource: FakeUserDataSource
private lateinit var sessionManager: ShoppingAppSessionManager
// class under test
private lateinit var authRepository: AuthRepository
@Before
fun createRepository() {
context = ApplicationProvider.getApplicationContext()
FirebaseApp.initializeApp(ApplicationProvider.getApplicationContext())
userLocalDataSource = FakeUserDataSource(userSeller)
authRemoteDataSource = FakeUserDataSource(userCustomer)
sessionManager = ShoppingAppSessionManager(ApplicationProvider.getApplicationContext())
authRepository = AuthRepository(
userLocalDataSource,
authRemoteDataSource,
sessionManager
)
}
@Test
fun login_getUserDetailFromSession() = runBlockingTest {
authRepository.login(userSeller, true)
val result = sessionManager.getUserDataFromSession()
assertThat(result["userName"], `is`(userSeller.name))
assertThat(result["userId"], `is`(userSeller.userId))
assertThat(result["userMobile"], `is`(userSeller.mobile))
}
@Test
fun singUp_addsUserToSources() = runBlockingTest {
authRepository.signUp(userCustomer)
val resultSession = sessionManager.getUserDataFromSession()
assertThat(resultSession["userName"], `is`(userCustomer.name))
assertThat(resultSession["userId"], `is`(userCustomer.userId))
assertThat(resultSession["userMobile"], `is`(userCustomer.mobile))
val localRes = userLocalDataSource.getUserById(userCustomer.userId)
assertThat(localRes, `is`(Success(userCustomer)))
val remoteRes = authRemoteDataSource.getUserById(userCustomer.userId)
assertThat(remoteRes, `is`(Success(userCustomer)))
}
@Test
fun checkEmailAndMobile_existingEmail_returnsError() {
authRemoteDataSource.updateEmailsAndMobiles("<EMAIL>", "+919999988888")
runOnUiThread {
runBlockingTest {
val result =
authRepository.checkEmailAndMobile("<EMAIL>", "+919685", context)
assertThat(result, `is`(SignUpErrors.SERR))
}
}
}
@Test
fun checkEmailAndMobile_existingMobile_returnsError() {
authRemoteDataSource.updateEmailsAndMobiles("<EMAIL>", "+919999988888")
runOnUiThread {
runBlockingTest {
val result =
authRepository.checkEmailAndMobile("<EMAIL>", "+919999988888", context)
assertThat(result, `is`(SignUpErrors.SERR))
}
}
}
@Test
fun checkEmailAndMobile_existingMobileAndEmail_returnsError() {
authRemoteDataSource.updateEmailsAndMobiles("<EMAIL>", "+919999988888")
runOnUiThread {
runBlockingTest {
val result =
authRepository.checkEmailAndMobile("<EMAIL>", "+919999988888", context)
assertThat(result, `is`(SignUpErrors.SERR))
}
}
}
@Test
fun checkEmailAndMobile_newData_returnsError() {
authRemoteDataSource.updateEmailsAndMobiles("<EMAIL>", "+919999988888")
runOnUiThread {
runBlockingTest {
val result =
authRepository.checkEmailAndMobile(
"<EMAIL>",
"+919999977777",
context
)
assertThat(result, `is`(SignUpErrors.NONE))
}
}
}
@Test
fun checkLogin_existingUser_returnsData() = runBlockingTest {
val result = authRepository.checkLogin(userCustomer.mobile, userCustomer.password)
assertThat(result, `is`(userCustomer))
}
@Test
fun checkLogin_newCredentials_returnsNull() = runBlockingTest {
val result = authRepository.checkLogin("+919879879879", "sdygt4")
assertThat(result, `is`(nullValue()))
}
@Test
fun signOut_clearsSessionAndData() = runBlockingTest {
authRepository.signOut()
val sessionRes = sessionManager.isLoggedIn()
val localRes = userLocalDataSource.getUserById(userSeller.userId)
assertThat(sessionRes, `is`(false))
if (localRes is Success)
assert(false)
else if (localRes is Error) {
assertEquals(localRes.exception.message, "User Not Found")
}
}
@Test
fun getLikes_returnsLikes() = runBlockingTest {
authRepository.signUp(userCustomer)
val res = authRepository.getLikesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data, `is`(userCustomer.likes))
} else {
assert(false)
}
}
@Test
fun likeProduct() = runBlockingTest {
authRepository.signUp(userCustomer)
authRepository.insertProductToLikes("some-id", userCustomer.userId)
val res = authRepository.getLikesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data?.size, `is`(1))
} else {
assert(false)
}
}
@Test
fun dislikeProduct() = runBlockingTest {
authRepository.signUp(userCustomer)
authRepository.insertProductToLikes("some-id", userCustomer.userId)
authRepository.removeProductFromLikes("some-id", userCustomer.userId)
val res = authRepository.getLikesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data?.contains("some-id"), `is`(false))
} else {
assert(false)
}
}
@Test
fun getAddresses() = runBlockingTest {
authRepository.signUp(userCustomer)
val res = authRepository.getAddressesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data, `is`(userCustomer.addresses))
} else {
assert(false)
}
}
@Test
fun addAddress() = runBlockingTest {
authRepository.signUp(userCustomer)
val address = UserData.Address(
"id123-add",
"namefirst",
"lname",
"IN",
"2341 weg",
"",
"kanopwe",
"up",
"209876",
"+919999988888"
)
authRepository.insertAddress(address, userCustomer.userId)
val res = authRepository.getAddressesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data?.size, `is`(1))
} else {
assert(false)
}
}
@Test
fun removeAddress() = runBlockingTest {
authRepository.signUp(userCustomer)
val address = UserData.Address(
"id123-add",
"namefirst",
"lname",
"IN",
"2341 weg",
"",
"kanopwe",
"up",
"209876",
"+919999988888"
)
authRepository.insertAddress(address, userCustomer.userId)
authRepository.deleteAddressById(address.addressId, userCustomer.userId)
val res = authRepository.getAddressesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data?.contains(address), `is`(false))
} else {
assert(false)
}
}
@Test
fun updateAddress() = runBlockingTest {
authRepository.signUp(userCustomer)
val address = UserData.Address(
"id123-add",
"namefirst",
"lname",
"IN",
"2341 weg",
"",
"kanopwe",
"up",
"209876",
"+919999988888"
)
val newAddress = UserData.Address(
"id123-add",
"namefirst",
"lname",
"IN",
"2341 wesfgeg",
"vdfg, heth",
"kanopwe",
"up",
"209876",
"+919999988888"
)
authRepository.insertAddress(address, userCustomer.userId)
authRepository.updateAddress(newAddress, userCustomer.userId)
val res = authRepository.getAddressesByUserId(userCustomer.userId)
if (res is Success) {
assertThat(res.data?.contains(newAddress), `is`(true))
} else {
assert(false)
}
}
@Test
fun addItemToCart() = runBlockingTest {
authRepository.signUp(userCustomer)
val item = UserData.CartItem(
"item-id-123",
"pro-122",
"owner-1213",
1,
"black",
7
)
authRepository.insertCartItemByUserId(item, userCustomer.userId)
val userRes = userLocalDataSource.getUserById(userCustomer.userId)
if (userRes is Success) {
val data = userRes.data
if (data != null) {
val cart = data.cart
assertThat(cart.contains(item), `is`(true))
} else {
assert(false)
}
} else {
assert(false)
}
}
@Test
fun removeItemFromCart() = runBlockingTest {
authRepository.signUp(userCustomer)
val item = UserData.CartItem(
"item-id-123",
"pro-122",
"owner-1213",
1,
"black",
7
)
authRepository.insertCartItemByUserId(item, userCustomer.userId)
authRepository.deleteCartItemByUserId(item.itemId, userCustomer.userId)
val userRes = userLocalDataSource.getUserById(userCustomer.userId)
if (userRes is Success) {
val data = userRes.data
if (data != null) {
val cart = data.cart
assertThat(cart.contains(item), `is`(false))
} else {
assert(false)
}
} else {
assert(false)
}
}
@Test
fun updateItemInCart() = runBlockingTest {
authRepository.signUp(userCustomer)
val item = UserData.CartItem(
"item-id-123",
"pro-122",
"owner-1213",
1,
"black",
7
)
val newItem = UserData.CartItem(
"item-id-123",
"pro-122",
"owner-1213",
5,
"black",
7
)
authRepository.insertCartItemByUserId(item, userCustomer.userId)
authRepository.updateCartItemByUserId(newItem, userCustomer.userId)
val userRes = userLocalDataSource.getUserById(userCustomer.userId)
if (userRes is Success) {
val data = userRes.data
if (data != null) {
val cart = data.cart
assertThat(cart.contains(newItem), `is`(true))
} else {
assert(false)
}
} else {
assert(false)
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/AddEditAddressViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepository
import com.vishalgaur.shoppingapp.data.utils.AddObjectStatus
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.getAddressId
import com.vishalgaur.shoppingapp.isPhoneValid
import com.vishalgaur.shoppingapp.isZipCodeValid
import com.vishalgaur.shoppingapp.ui.AddAddressViewErrors
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class AddEditAddressViewModel(application: Application) : AndroidViewModel(application) {
private val authRepository = (application as ShoppingApplication).authRepository
private val sessionManager = ShoppingAppSessionManager(application.applicationContext)
private val currentUser = sessionManager.getUserIdFromSession()
private val _isEdit = MutableLiveData<Boolean>()
val isEdit: LiveData<Boolean> get() = _isEdit
private val _addressId = MutableLiveData<String>()
val addressId: LiveData<String> get() = _addressId
private val _dataStatus = MutableLiveData<StoreDataStatus>()
val dataStatus: LiveData<StoreDataStatus> get() = _dataStatus
private val _errorStatus = MutableLiveData<List<AddAddressViewErrors>>()
val errorStatus: LiveData<List<AddAddressViewErrors>> get() = _errorStatus
private val _addAddressStatus = MutableLiveData<AddObjectStatus?>()
val addAddressStatus: LiveData<AddObjectStatus?> get() = _addAddressStatus
private val _addressData = MutableLiveData<UserData.Address>()
val addressData: LiveData<UserData.Address> get() = _addressData
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
val newAddressData = MutableLiveData<UserData.Address>()
init {
_errorStatus.value = mutableListOf()
}
fun setIsEdit(state: Boolean) {
_isEdit.value = state
}
fun setAddressData(addressId: String) {
_addressId.value = addressId
viewModelScope.launch {
Log.d(TAG, "onLoad: Getting Address Data")
_dataStatus.value = StoreDataStatus.LOADING
val res = async { authRepository.getAddressesByUserId(currentUser!!) }
val addRes = res.await()
if (addRes is Success) {
val addData = addRes.data?.find { address -> address.addressId == addressId }
_addressData.value = addData ?: UserData.Address()
Log.d(TAG, "onLoad: Success")
_dataStatus.value = StoreDataStatus.DONE
} else {
_dataStatus.value = StoreDataStatus.ERROR
_addressData.value = UserData.Address()
if (addRes is Error)
Log.d(TAG, "onLoad: Error, ${addRes.exception.message}")
}
}
}
fun submitAddress(
countryCode: String,
firstName: String,
lastName: String,
streetAdd: String,
streetAdd2: String,
city: String,
state: String,
zipCode: String,
phoneNumber: String
) {
val errorsList = mutableListOf<AddAddressViewErrors>()
if (firstName.isBlank() || lastName.isBlank() || streetAdd.isBlank() || city.isBlank() || state.isBlank() || zipCode.isBlank() || phoneNumber.isBlank())
errorsList.add(AddAddressViewErrors.EMPTY)
if (firstName.isBlank()) errorsList.add(AddAddressViewErrors.ERR_FNAME_EMPTY)
if (lastName.isBlank()) errorsList.add(AddAddressViewErrors.ERR_LNAME_EMPTY)
if (streetAdd.isBlank()) errorsList.add(AddAddressViewErrors.ERR_STR1_EMPTY)
if (city.isBlank()) errorsList.add(AddAddressViewErrors.ERR_CITY_EMPTY)
if (state.isBlank()) errorsList.add(AddAddressViewErrors.ERR_STATE_EMPTY)
if (zipCode.isBlank()) errorsList.add(AddAddressViewErrors.ERR_ZIP_EMPTY)
else if (!isZipCodeValid(zipCode)) errorsList.add(AddAddressViewErrors.ERR_ZIP_INVALID)
if (phoneNumber.isBlank()) errorsList.add(AddAddressViewErrors.ERR_PHONE_EMPTY)
else if (!isPhoneValid(phoneNumber)) errorsList.add(AddAddressViewErrors.ERR_PHONE_INVALID)
_errorStatus.value = errorsList
if (errorsList.isEmpty()) {
val addressId = if (_isEdit.value == true) _addressId.value!! else
getAddressId(currentUser!!)
val newAddress = UserData.Address(
addressId,
firstName.trim(),
lastName.trim(),
countryCode.trim(),
streetAdd.trim(),
streetAdd2.trim(),
city.trim(),
state.trim(),
zipCode.trim(),
"+91" + phoneNumber.trim()
)
newAddressData.value = newAddress
if (_isEdit.value == true) {
updateAddress()
} else {
insertAddress()
}
}
}
private fun updateAddress() {
viewModelScope.launch {
if (newAddressData.value != null && _addressData.value != null) {
_addAddressStatus.value = AddObjectStatus.ADDING
val updateRes = async {
authRepository.updateAddress(newAddressData.value!!, currentUser!!)
}
val res = updateRes.await()
if (res is Success) {
authRepository.hardRefreshUserData()
Log.d(TAG, "onUpdate: Success")
_addAddressStatus.value = AddObjectStatus.DONE
} else {
Log.d(TAG, "onUpdate: Some error occurred!")
_addAddressStatus.value = AddObjectStatus.ERR_ADD
if (res is Error)
Log.d(TAG, "onUpdate: Error, ${res.exception}")
}
} else {
Log.d(TAG, "Address Null, Cannot Update!")
}
}
}
private fun insertAddress() {
viewModelScope.launch {
if (newAddressData.value != null) {
_addAddressStatus.value = AddObjectStatus.ADDING
val deferredRes = async {
authRepository.insertAddress(newAddressData.value!!, currentUser!!)
}
val res = deferredRes.await()
if (res is Success) {
authRepository.hardRefreshUserData()
Log.d(TAG, "onInsertAddress: Success")
_addAddressStatus.value = AddObjectStatus.DONE
} else {
_addAddressStatus.value = AddObjectStatus.ERR_ADD
if (res is Error) {
Log.d(TAG, "onInsertAddress: Error, ${res.exception.message}")
}
}
} else {
Log.d(TAG, "Address is Null, Cannot Add!")
}
}
}
companion object {
private const val TAG = "AddAddressViewModel"
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/CartFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ConcatAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentCartBinding
import com.vishalgaur.shoppingapp.databinding.LayoutCircularLoaderBinding
import com.vishalgaur.shoppingapp.databinding.LayoutPriceCardBinding
import com.vishalgaur.shoppingapp.viewModels.OrderViewModel
private const val TAG = "CartFragment"
class CartFragment : Fragment() {
private lateinit var binding: FragmentCartBinding
private val orderViewModel: OrderViewModel by activityViewModels()
private lateinit var itemsAdapter: CartItemAdapter
private lateinit var concatAdapter: ConcatAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentCartBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
orderViewModel.getUserLikes()
orderViewModel.getCartItems()
}
private fun setViews() {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.cartAppBar.topAppBar.title = getString(R.string.cart_fragment_label)
binding.cartEmptyTextView.visibility = View.GONE
binding.cartCheckOutBtn.setOnClickListener {
navigateToSelectAddress()
}
if (context != null) {
setItemsAdapter(orderViewModel.cartItems.value)
concatAdapter = ConcatAdapter(itemsAdapter, PriceCardAdapter())
binding.cartProductsRecyclerView.adapter = concatAdapter
}
}
private fun setObservers() {
orderViewModel.dataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.cartProductsRecyclerView.visibility = View.GONE
binding.cartCheckOutBtn.visibility = View.GONE
binding.cartEmptyTextView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
else -> {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
}
}
}
orderViewModel.dataStatus.observe(viewLifecycleOwner) { status ->
if (status != null && status != StoreDataStatus.LOADING) {
orderViewModel.cartProducts.observe(viewLifecycleOwner) { itemList ->
if (itemList.isNotEmpty()) {
updateAdapter()
binding.cartEmptyTextView.visibility = View.GONE
binding.cartProductsRecyclerView.visibility = View.VISIBLE
binding.cartCheckOutBtn.visibility = View.VISIBLE
} else if (itemList.isEmpty()) {
binding.cartProductsRecyclerView.visibility = View.GONE
binding.cartCheckOutBtn.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.cartEmptyTextView.visibility = View.VISIBLE
}
}
}
}
orderViewModel.cartItems.observe(viewLifecycleOwner) { items ->
if (items.isNotEmpty()) {
updateAdapter()
}
}
orderViewModel.priceList.observe(viewLifecycleOwner) {
if (it.isNotEmpty()) {
updateAdapter()
}
}
orderViewModel.userLikes.observe(viewLifecycleOwner) {
if (it.isNotEmpty()) {
updateAdapter()
}
}
}
private fun updateAdapter() {
val items = orderViewModel.cartItems.value ?: emptyList()
val likeList = orderViewModel.userLikes.value ?: emptyList()
val prosList = orderViewModel.cartProducts.value ?: emptyList()
itemsAdapter.apply {
data = items
proList = prosList
likesList = likeList
}
concatAdapter = ConcatAdapter(itemsAdapter, PriceCardAdapter())
binding.cartProductsRecyclerView.adapter = concatAdapter
binding.cartProductsRecyclerView.adapter?.notifyDataSetChanged()
}
private fun setItemsAdapter(itemList: List<UserData.CartItem>?) {
val items = itemList ?: emptyList()
val likesList = orderViewModel.userLikes.value ?: emptyList()
val proList = orderViewModel.cartProducts.value ?: emptyList()
itemsAdapter = CartItemAdapter(requireContext(), items, proList, likesList)
itemsAdapter.onClickListener = object : CartItemAdapter.OnClickListener {
override fun onLikeClick(productId: String) {
Log.d(TAG, "onToggle Like Clicked")
orderViewModel.toggleLikeProduct(productId)
}
override fun onDeleteClick(itemId: String, itemBinding: LayoutCircularLoaderBinding) {
Log.d(TAG, "onDelete: initiated")
showDeleteDialog(itemId, itemBinding)
}
override fun onPlusClick(itemId: String) {
Log.d(TAG, "onPlus: Increasing quantity")
orderViewModel.setQuantityOfItem(itemId, 1)
}
override fun onMinusClick(itemId: String, currQuantity: Int,itemBinding: LayoutCircularLoaderBinding) {
Log.d(TAG, "onMinus: decreasing quantity")
if (currQuantity == 1) {
showDeleteDialog(itemId, itemBinding)
} else {
orderViewModel.setQuantityOfItem(itemId, -1)
}
}
}
}
private fun navigateToSelectAddress() {
findNavController().navigate(R.id.action_cartFragment_to_selectAddressFragment)
}
private fun showDeleteDialog(itemId: String, itemBinding: LayoutCircularLoaderBinding) {
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.delete_dialog_title_text))
.setMessage(getString(R.string.delete_cart_item_message_text))
.setNegativeButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
itemBinding.loaderFrameLayout.visibility = View.GONE
}
.setPositiveButton(getString(R.string.delete_dialog_delete_btn_text)) { dialog, _ ->
orderViewModel.deleteItemFromCart(itemId)
dialog.cancel()
}.setOnCancelListener {
itemBinding.loaderFrameLayout.visibility = View.GONE
}
.show()
}
}
inner class PriceCardAdapter : RecyclerView.Adapter<PriceCardAdapter.ViewHolder>() {
inner class ViewHolder(private val priceCardBinding: LayoutPriceCardBinding) :
RecyclerView.ViewHolder(priceCardBinding.root) {
fun bind() {
priceCardBinding.priceItemsLabelTv.text = getString(
R.string.price_card_items_string,
orderViewModel.getItemsCount().toString()
)
priceCardBinding.priceItemsAmountTv.text =
getString(R.string.price_text, orderViewModel.getItemsPriceTotal().toString())
priceCardBinding.priceShippingAmountTv.text = getString(R.string.price_text, "0")
priceCardBinding.priceChargesAmountTv.text = getString(R.string.price_text, "0")
priceCardBinding.priceTotalAmountTv.text =
getString(R.string.price_text, orderViewModel.getItemsPriceTotal().toString())
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutPriceCardBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind()
}
override fun getItemCount() = 1
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/AccountFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.databinding.FragmentAccountBinding
import com.vishalgaur.shoppingapp.ui.loginSignup.LoginSignupActivity
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
private const val TAG = "AccountFragment"
class AccountFragment : Fragment() {
private lateinit var binding: FragmentAccountBinding
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAccountBinding.inflate(layoutInflater)
setViews()
return binding.root
}
private fun setViews() {
binding.accountTopAppBar.topAppBar.title = getString(R.string.account_fragment_title)
binding.accountProfileTv.setOnClickListener {
Log.d(TAG, "Profile Selected")
findNavController().navigate(R.id.action_accountFragment_to_profileFragment)
}
binding.accountOrdersTv.setOnClickListener {
Log.d(TAG, "Orders Selected")
findNavController().navigate(R.id.action_accountFragment_to_ordersFragment)
}
binding.accountAddressTv.setOnClickListener {
Log.d(TAG, "Address Selected")
findNavController().navigate(R.id.action_accountFragment_to_addressFragment)
}
binding.accountSignOutTv.setOnClickListener {
Log.d(TAG, "Sign Out Selected")
showSignOutDialog()
}
}
private fun showSignOutDialog() {
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.sign_out_dialog_title_text))
.setMessage(getString(R.string.sign_out_dialog_message_text))
.setNegativeButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.dialog_sign_out_btn_text)) { dialog, _ ->
viewModel.signOut()
navigateToSignUpActivity()
dialog.cancel()
}
.show()
}
}
private fun navigateToSignUpActivity() {
val homeIntent = Intent(context, LoginSignupActivity::class.java)
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context?.startActivity(homeIntent)
requireActivity().finish()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/remote/AuthRemoteDataSource.kt
package com.vishalgaur.shoppingapp.data.source.remote
import android.util.Log
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.UserDataSource
import com.vishalgaur.shoppingapp.data.utils.EmailMobileData
import com.vishalgaur.shoppingapp.data.utils.OrderStatus
import kotlinx.coroutines.tasks.await
class AuthRemoteDataSource : UserDataSource {
private val firebaseDb: FirebaseFirestore = Firebase.firestore
private fun usersCollectionRef() = firebaseDb.collection(USERS_COLLECTION)
private fun allEmailsMobilesRef() =
firebaseDb.collection(USERS_COLLECTION).document(EMAIL_MOBILE_DOC)
override suspend fun getUserById(userId: String): Result<UserData?> {
val resRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
return if (!resRef.isEmpty) {
Success(resRef.toObjects(UserData::class.java)[0])
} else {
Error(Exception("User Not Found!"))
}
}
override suspend fun addUser(userData: UserData) {
usersCollectionRef().add(userData.toHashMap())
.addOnSuccessListener {
Log.d(TAG, "Doc added")
}
.addOnFailureListener { e ->
Log.d(TAG, "firestore error occurred: $e")
}
}
override suspend fun getUserByMobile(phoneNumber: String): UserData =
usersCollectionRef().whereEqualTo(USERS_MOBILE_FIELD, phoneNumber).get().await()
.toObjects(UserData::class.java)[0]
override suspend fun getOrdersByUserId(userId: String): Result<List<UserData.OrderItem>?> {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
return if (!userRef.isEmpty) {
val userData = userRef.documents[0].toObject(UserData::class.java)
Success(userData!!.orders)
} else {
Error(Exception("User Not Found!"))
}
}
override suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?> {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
return if (!userRef.isEmpty) {
val userData = userRef.documents[0].toObject(UserData::class.java)
Success(userData!!.addresses)
} else {
Error(Exception("User Not Found!"))
}
}
override suspend fun getLikesByUserId(userId: String): Result<List<String>?> {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
return if (!userRef.isEmpty) {
val userData = userRef.documents[0].toObject(UserData::class.java)
Success(userData!!.likes)
} else {
Error(Exception("User Not Found!"))
}
}
override suspend fun getUserByMobileAndPassword(
mobile: String,
password: String
): MutableList<UserData> =
usersCollectionRef().whereEqualTo(USERS_MOBILE_FIELD, mobile)
.whereEqualTo(USERS_PWD_FIELD, password).get().await().toObjects(UserData::class.java)
override suspend fun likeProduct(productId: String, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
usersCollectionRef().document(docId)
.update(USERS_LIKES_FIELD, FieldValue.arrayUnion(productId))
}
}
override suspend fun dislikeProduct(productId: String, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
usersCollectionRef().document(docId)
.update(USERS_LIKES_FIELD, FieldValue.arrayRemove(productId))
}
}
override suspend fun insertAddress(newAddress: UserData.Address, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
usersCollectionRef().document(docId)
.update(USERS_ADDRESSES_FIELD, FieldValue.arrayUnion(newAddress.toHashMap()))
}
}
override suspend fun updateAddress(newAddress: UserData.Address, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
val oldAddressList =
userRef.documents[0].toObject(UserData::class.java)?.addresses?.toMutableList()
val idx = oldAddressList?.indexOfFirst { it.addressId == newAddress.addressId } ?: -1
if (idx != -1) {
oldAddressList?.set(idx, newAddress)
}
usersCollectionRef().document(docId)
.update(USERS_ADDRESSES_FIELD, oldAddressList?.map { it.toHashMap() })
}
}
override suspend fun deleteAddress(addressId: String, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
val oldAddressList =
userRef.documents[0].toObject(UserData::class.java)?.addresses?.toMutableList()
val idx = oldAddressList?.indexOfFirst { it.addressId == addressId } ?: -1
if (idx != -1) {
oldAddressList?.removeAt(idx)
}
usersCollectionRef().document(docId)
.update(USERS_ADDRESSES_FIELD, oldAddressList?.map { it.toHashMap() })
}
}
override suspend fun insertCartItem(newItem: UserData.CartItem, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
usersCollectionRef().document(docId)
.update(USERS_CART_FIELD, FieldValue.arrayUnion(newItem.toHashMap()))
}
}
override suspend fun updateCartItem(item: UserData.CartItem, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
val oldCart =
userRef.documents[0].toObject(UserData::class.java)?.cart?.toMutableList()
val idx = oldCart?.indexOfFirst { it.itemId == item.itemId } ?: -1
if (idx != -1) {
oldCart?.set(idx, item)
}
usersCollectionRef().document(docId)
.update(USERS_CART_FIELD, oldCart?.map { it.toHashMap() })
}
}
override suspend fun deleteCartItem(itemId: String, userId: String) {
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
val oldCart =
userRef.documents[0].toObject(UserData::class.java)?.cart?.toMutableList()
val idx = oldCart?.indexOfFirst { it.itemId == itemId } ?: -1
if (idx != -1) {
oldCart?.removeAt(idx)
}
usersCollectionRef().document(docId)
.update(USERS_CART_FIELD, oldCart?.map { it.toHashMap() })
}
}
override suspend fun placeOrder(newOrder: UserData.OrderItem, userId: String) {
// add order to customer and
// specific items to their owners
// empty customers cart
val ownerProducts: MutableMap<String, MutableList<UserData.CartItem>> = mutableMapOf()
for (item in newOrder.items) {
if (!ownerProducts.containsKey(item.ownerId)) {
ownerProducts[item.ownerId] = mutableListOf()
}
ownerProducts[item.ownerId]?.add(item)
}
ownerProducts.forEach { (ownerId, items) ->
run {
val itemPrices = mutableMapOf<String, Double>()
items.forEach { item ->
itemPrices[item.itemId] = newOrder.itemsPrices[item.itemId] ?: 0.0
}
val ownerOrder = UserData.OrderItem(
newOrder.orderId,
userId,
items,
itemPrices,
newOrder.deliveryAddress,
newOrder.shippingCharges,
newOrder.paymentMethod,
newOrder.orderDate,
OrderStatus.CONFIRMED.name
)
val ownerRef =
usersCollectionRef().whereEqualTo(USERS_ID_FIELD, ownerId).get().await()
if (!ownerRef.isEmpty) {
val docId = ownerRef.documents[0].id
usersCollectionRef().document(docId)
.update(USERS_ORDERS_FIELD, FieldValue.arrayUnion(ownerOrder.toHashMap()))
}
}
}
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
usersCollectionRef().document(docId)
.update(USERS_ORDERS_FIELD, FieldValue.arrayUnion(newOrder.toHashMap()))
usersCollectionRef().document(docId)
.update(USERS_CART_FIELD, ArrayList<UserData.CartItem>())
}
}
override suspend fun setStatusOfOrderByUserId(orderId: String, userId: String, status: String) {
// update on customer and owner
val userRef = usersCollectionRef().whereEqualTo(USERS_ID_FIELD, userId).get().await()
if (!userRef.isEmpty) {
val docId = userRef.documents[0].id
val ordersList =
userRef.documents[0].toObject(UserData::class.java)?.orders?.toMutableList()
val idx = ordersList?.indexOfFirst { it.orderId == orderId } ?: -1
if (idx != -1) {
val orderData = ordersList?.get(idx)
if (orderData != null) {
usersCollectionRef().document(docId)
.update(USERS_ORDERS_FIELD, FieldValue.arrayRemove(orderData.toHashMap()))
orderData.status = status
usersCollectionRef().document(docId)
.update(USERS_ORDERS_FIELD, FieldValue.arrayUnion(orderData.toHashMap()))
// updating customer status
val custRef =
usersCollectionRef().whereEqualTo(USERS_ID_FIELD, orderData.customerId)
.get().await()
if (!custRef.isEmpty) {
val did = custRef.documents[0].id
val orders =
custRef.documents[0].toObject(UserData::class.java)?.orders?.toMutableList()
val pos = orders?.indexOfFirst { it.orderId == orderId } ?: -1
if (pos != -1) {
val order = orders?.get(pos)
if (order != null) {
usersCollectionRef().document(did).update(
USERS_ORDERS_FIELD,
FieldValue.arrayRemove(order.toHashMap())
)
order.status = status
usersCollectionRef().document(did).update(
USERS_ORDERS_FIELD,
FieldValue.arrayUnion(order.toHashMap())
)
}
}
}
}
}
}
}
override fun updateEmailsAndMobiles(email: String, mobile: String) {
allEmailsMobilesRef().update(EMAIL_MOBILE_EMAIL_FIELD, FieldValue.arrayUnion(email))
allEmailsMobilesRef().update(EMAIL_MOBILE_MOB_FIELD, FieldValue.arrayUnion(mobile))
}
override suspend fun getEmailsAndMobiles() = allEmailsMobilesRef().get().await().toObject(
EmailMobileData::class.java
)
companion object {
private const val USERS_COLLECTION = "users"
private const val USERS_ID_FIELD = "userId"
private const val USERS_ADDRESSES_FIELD = "addresses"
private const val USERS_LIKES_FIELD = "likes"
private const val USERS_CART_FIELD = "cart"
private const val USERS_ORDERS_FIELD = "orders"
private const val USERS_MOBILE_FIELD = "mobile"
private const val USERS_PWD_FIELD = "<PASSWORD>"
private const val EMAIL_MOBILE_DOC = "emailAndMobiles"
private const val EMAIL_MOBILE_EMAIL_FIELD = "emails"
private const val EMAIL_MOBILE_MOB_FIELD = "mobiles"
private const val TAG = "AuthRemoteDataSource"
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/viewModels/AuthViewModelTest.kt
package com.vishalgaur.shoppingapp.viewModels
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.getOrAwaitValue
import com.vishalgaur.shoppingapp.ui.LoginViewErrors
import com.vishalgaur.shoppingapp.ui.SignUpViewErrors
import org.hamcrest.Matchers.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AuthViewModelTest {
private lateinit var authViewModel: AuthViewModel
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
authViewModel = AuthViewModel(ApplicationProvider.getApplicationContext())
}
@Test
fun signUpSubmitData_noData_returnsEmptyError() {
val name = ""
val mobile = ""
val email = ""
val pwd1 = ""
val pwd2 = ""
val isAccepted = false
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.ERR_EMPTY))
assertThat(authViewModel.userData.value, `is`(nullValue()))
}
@Test
fun signUpSubmitData_notAccepted_returnsNotAccError() {
val name = "uigbivs ihgfdsg"
val mobile = "9988665555"
val email = "<EMAIL>"
val pwd1 = "<PASSWORD>"
val pwd2 = "<PASSWORD>"
val isAccepted = false
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.ERR_NOT_ACC))
assertThat(authViewModel.userData.value, `is`(nullValue()))
}
@Test
fun signUpSubmitData_pwdNotEq_returnsPwdError() {
val name = "<NAME>"
val mobile = "9988665555"
val email = "<EMAIL>"
val pwd1 = "<PASSWORD>"
val pwd2 = "<PASSWORD>"
val isAccepted = false
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.ERR_PWD12NS))
assertThat(authViewModel.userData.value, `is`(nullValue()))
}
@Test
fun signUpSubmitData_invalidEmail_returnsEmailError() {
val name = "<NAME>"
val mobile = "9988665555"
val email = "<EMAIL>"
val pwd1 = "<PASSWORD>"
val pwd2 = "<PASSWORD>"
val isAccepted = true
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.ERR_EMAIL))
assertThat(authViewModel.userData.value, `is`(nullValue()))
}
@Test
fun signUpSubmitData_invalidMobile_returnsMobError() {
val name = "<NAME>"
val mobile = "9988665fng55"
val email = "<EMAIL>"
val pwd1 = "<PASSWORD>"
val pwd2 = "<PASSWORD>"
val isAccepted = true
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.ERR_MOBILE))
assertThat(authViewModel.userData.value, `is`(nullValue()))
}
@Test
fun signUpSubmitData_invalidEmailMobile_returnsEmailMobError() {
val name = "<NAME>"
val mobile = "9988665fng55"
val email = "<EMAIL>"
val pwd1 = "<PASSWORD>"
val pwd2 = "<PASSWORD>"
val isAccepted = true
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.ERR_EMAIL_MOBILE))
assertThat(authViewModel.userData.value, `is`(nullValue()))
}
@Test
fun signUpSubmitData_validData_returnsNoError() {
val name = " <NAME>"
val mobile = " 9988665755"
val email = "<EMAIL> "
val pwd1 = "<PASSWORD>"
val pwd2 = "<PASSWORD>"
val isAccepted = true
val isSeller = false
authViewModel.signUpSubmitData(name, mobile, email, pwd1, pwd2, isAccepted, isSeller)
val result = authViewModel.errorStatus.getOrAwaitValue()
val dataRes = authViewModel.userData.getOrAwaitValue()
assertThat(result, `is`(SignUpViewErrors.NONE))
assertThat(dataRes, `is`(notNullValue()))
assertThat(dataRes.name, `is`("uigbivs ihgfdsg"))
}
@Test
fun loginSubmitData_noData_returnsEmptyError() {
val mobile = ""
val pwd = ""
authViewModel.loginSubmitData(mobile, pwd)
val result = authViewModel.errorStatusLoginFragment.getOrAwaitValue()
assertThat(result, `is`(LoginViewErrors.ERR_EMPTY))
}
@Test
fun loginSubmitData_invalidMobile_returnsMobileError() {
val mobile = "9fwd988556699"
val pwd = "123"
authViewModel.loginSubmitData(mobile, pwd)
val result = authViewModel.errorStatusLoginFragment.getOrAwaitValue()
assertThat(result, `is`(LoginViewErrors.ERR_MOBILE))
}
@Test
fun loginSubmitData_validData_returnsNoError() {
val mobile = "9988556699"
val pwd = "123"
authViewModel.loginSubmitData(mobile, pwd)
val result = authViewModel.errorStatusLoginFragment.getOrAwaitValue()
assertThat(result, `is`(LoginViewErrors.NONE))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/utils/ProductUtils.kt
package com.vishalgaur.shoppingapp.data.utils
val ShoeSizes = mapOf(
"UK4" to 4,
"UK5" to 5,
"UK6" to 6,
"UK7" to 7,
"UK8" to 8,
"UK9" to 9,
"UK10" to 10,
"UK11" to 11,
"UK12" to 12
)
val ShoeColors = mapOf(
"black" to "#000000",
"white" to "#FFFFFF",
"red" to "#FF0000",
"green" to "#00FF00",
"blue" to "#0000FF",
"yellow" to "#FFFF00",
"cyan" to "#00FFFF",
"magenta" to "#FF00FF"
)
val ProductCategories = arrayOf("Shoes", "Slippers")<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ServiceLocator.kt
package com.vishalgaur.shoppingapp
import android.content.Context
import androidx.annotation.VisibleForTesting
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.source.ProductDataSource
import com.vishalgaur.shoppingapp.data.source.UserDataSource
import com.vishalgaur.shoppingapp.data.source.local.ProductsLocalDataSource
import com.vishalgaur.shoppingapp.data.source.local.ShoppingAppDatabase
import com.vishalgaur.shoppingapp.data.source.local.UserLocalDataSource
import com.vishalgaur.shoppingapp.data.source.remote.AuthRemoteDataSource
import com.vishalgaur.shoppingapp.data.source.remote.ProductsRemoteDataSource
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepository
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepository
object ServiceLocator {
private var database: ShoppingAppDatabase? = null
private val lock = Any()
@Volatile
var authRepository: AuthRepoInterface? = null
@VisibleForTesting set
@Volatile
var productsRepository: ProductsRepoInterface? = null
@VisibleForTesting set
fun provideAuthRepository(context: Context): AuthRepoInterface {
synchronized(this) {
return authRepository ?: createAuthRepository(context)
}
}
fun provideProductsRepository(context: Context): ProductsRepoInterface {
synchronized(this) {
return productsRepository ?: createProductsRepository(context)
}
}
@VisibleForTesting
fun resetRepository() {
synchronized(lock) {
database?.apply {
clearAllTables()
close()
}
database = null
authRepository = null
}
}
private fun createProductsRepository(context: Context): ProductsRepoInterface {
val newRepo =
ProductsRepository(ProductsRemoteDataSource(), createProductsLocalDataSource(context))
productsRepository = newRepo
return newRepo
}
private fun createAuthRepository(context: Context): AuthRepoInterface {
val appSession = ShoppingAppSessionManager(context.applicationContext)
val newRepo =
AuthRepository(createUserLocalDataSource(context), AuthRemoteDataSource(), appSession)
authRepository = newRepo
return newRepo
}
private fun createProductsLocalDataSource(context: Context): ProductDataSource {
val database = database ?: ShoppingAppDatabase.getInstance(context.applicationContext)
return ProductsLocalDataSource(database.productsDao())
}
private fun createUserLocalDataSource(context: Context): UserDataSource {
val database = database ?: ShoppingAppDatabase.getInstance(context.applicationContext)
return UserLocalDataSource(database.userDao())
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/OtpViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.util.Log
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.firebase.FirebaseException
import com.google.firebase.FirebaseTooManyRequestsException
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.PhoneAuthOptions
import com.google.firebase.auth.PhoneAuthProvider
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.ui.OTPStatus
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
private const val TAG = "OtpViewModel"
class OtpViewModel(application: Application, private val uData: UserData) :
AndroidViewModel(application) {
private val _otpStatus = MutableLiveData<OTPStatus>()
val otpStatus: LiveData<OTPStatus> get() = _otpStatus
private val _isOTPSent = MutableLiveData<Boolean>()
val isOTPSent: LiveData<Boolean> get() = _isOTPSent
private val authRepository = (application as ShoppingApplication).authRepository
var isUserLoggedIn = MutableLiveData(false)
var storedVerificationId: String? = ""
private var verificationInProgress = false
private lateinit var resendToken: PhoneAuthProvider.ForceResendingToken
init {
_isOTPSent.value = false
}
fun verifyOTP(otp: String) {
viewModelScope.launch {
verifyPhoneWithCode(storedVerificationId!!, otp, isUserLoggedIn)
}
}
fun signUp() {
viewModelScope.launch {
authRepository.signUp(uData)
}
}
fun login(rememberMe: Boolean) {
viewModelScope.launch {
authRepository.login(uData, rememberMe)
}
}
fun verifyPhoneOTPStart(phoneNumber: String, activity: FragmentActivity) {
val options = PhoneAuthOptions.newBuilder(authRepository.getFirebaseAuth())
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(activity) // Activity (for callback binding)
.setCallbacks(callbacks) // OnVerificationStateChangedCallbacks
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
verificationInProgress = true
}
private val callbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(credential: PhoneAuthCredential) {
Log.d(TAG, "onVerificationCompleted:$credential")
authRepository.signInWithPhoneAuthCredential(credential, isUserLoggedIn, application.applicationContext)
}
override fun onVerificationFailed(e: FirebaseException) {
Log.w(TAG, "onVerificationFailed", e)
if (e is FirebaseAuthInvalidCredentialsException) {
Log.w(TAG, "onVerificationFailed, invalid request, ", e)
} else if (e is FirebaseTooManyRequestsException) {
Log.w(TAG, "onVerificationFailed, sms quota exceeded, ", e)
}
}
override fun onCodeSent(
verificationId: String,
token: PhoneAuthProvider.ForceResendingToken
) {
// Save verification ID and resending token so we can use them later
storedVerificationId = verificationId
resendToken = token
Log.w(TAG, "OTP SENT")
_isOTPSent.value = true
}
}
private fun verifyPhoneWithCode(verificationId: String, code: String, isUserLoggedIn: MutableLiveData<Boolean>) {
try {
val credential = PhoneAuthProvider.getCredential(verificationId, code)
authRepository.signInWithPhoneAuthCredential(credential, isUserLoggedIn, getApplication<ShoppingApplication>().applicationContext)
} catch (e: Exception) {
Log.d(TAG, "onVerifyWithCode: Exception Occurred: ${e.message}")
}
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/FakeProductsDataSource.kt
package com.vishalgaur.shoppingapp.data.source
import android.net.Uri
import androidx.core.net.toUri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
class FakeProductsDataSource(private var products: MutableList<Product>? = mutableListOf()) :
ProductDataSource {
private val imagesStorage = mutableListOf<String>()
override fun observeProducts(): LiveData<Result<List<Product>>?> {
products?.let { pros ->
val res = MutableLiveData(pros)
return Transformations.map(res) {
Success(it.toList())
}
}
return MutableLiveData(Error(Exception()))
}
override fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?> {
products?.let { allPros ->
val pros = allPros.filter { pr -> pr.owner == ownerId }
val res = MutableLiveData(pros)
return Transformations.map(res) {
Success(it.toList())
}
}
return MutableLiveData(Error(Exception()))
}
override suspend fun getAllProducts(): Result<List<Product>> {
products?.let {
return Success(it)
}
return Error(Exception("Products Not Found"))
}
override suspend fun refreshProducts() {
// No implementation
}
override suspend fun getProductById(productId: String): Result<Product> {
products?.let {
val res = it.filter { product -> product.productId == productId }
return if (res.isNotEmpty()) {
Success(res[0])
} else {
Error(Exception("Product Not Found"))
}
}
return Error(Exception("Product Not Found"))
}
override suspend fun insertProduct(newProduct: Product) {
products?.add(newProduct)
}
override suspend fun updateProduct(proData: Product) {
products?.let {
val pos = it.indexOfFirst { product -> proData.productId == product.productId }
it[pos] = proData
}
}
override suspend fun deleteProduct(productId: String) {
products?.let {
val pos = it.indexOfFirst { product -> productId == product.productId }
if (pos >= 0)
it.removeAt(pos)
else throw Exception("Product Not Found")
}
}
override suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>> {
val res = products?.filter { product ->
product.owner == ownerId
}
return if (res != null) {
Success(res)
} else {
Success(emptyList())
}
}
override suspend fun deleteAllProducts() {
products = mutableListOf()
}
override suspend fun insertMultipleProducts(data: List<Product>) {
products?.addAll(data)
}
override suspend fun uploadImage(uri: Uri, fileName: String): Uri {
val res = uri.toString() + fileName
if (res.contains("invalidinvalidinvalid")) {
throw Exception("Error uploading Images")
}
imagesStorage.add(res)
return res.toUri()
}
override fun revertUpload(fileName: String) {
val pos = imagesStorage.indexOfFirst { imageRef ->
imageRef.contains(fileName)
}
if (pos >= 0) {
imagesStorage.removeAt(pos)
}
}
override fun deleteImage(imgUrl: String) {
imagesStorage.remove(imgUrl)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/RecyclerViewPaddingItemDecoration.kt
package com.vishalgaur.shoppingapp.ui
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class RecyclerViewPaddingItemDecoration(private val context: Context) :
RecyclerView.ItemDecoration() {
private val paddingSpace = 16
override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
super.getItemOffsets(outRect, view, parent, state)
outRect.set(paddingSpace, paddingSpace, paddingSpace, paddingSpace)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/utils/ObjectListTypeConvertor.kt
package com.vishalgaur.shoppingapp.data.utils
import androidx.room.TypeConverter
import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.vishalgaur.shoppingapp.data.UserData
class ObjectListTypeConvertor {
@TypeConverter
fun stringToAddressObjectList(data: String?): List<UserData.Address> {
if (data.isNullOrBlank()) {
return emptyList()
}
val listType = object : TypeToken<List<UserData.Address>>() {}.type
val gson = Gson()
return gson.fromJson(data, listType)
}
@TypeConverter
fun addressObjectListToString(addressList: List<UserData.Address>): String {
if (addressList.isEmpty()) {
return ""
}
val gson = Gson()
val listType = object : TypeToken<List<UserData.Address>>() {}.type
return gson.toJson(addressList, listType)
}
@TypeConverter
fun stringToCartObjectList(data: String?): List<UserData.CartItem> {
if (data.isNullOrBlank()) {
return emptyList()
}
val listType = object : TypeToken<List<UserData.CartItem>>() {}.type
val gson = Gson()
return gson.fromJson(data, listType)
}
@TypeConverter
fun cartObjectListToString(cartList: List<UserData.CartItem>): String {
if (cartList.isEmpty()) {
return ""
}
val gson = Gson()
val listType = object : TypeToken<List<UserData.CartItem>>() {}.type
return gson.toJson(cartList, listType)
}
@TypeConverter
fun stringToOrderObjectList(data: String?): List<UserData.OrderItem> {
if (data.isNullOrBlank()) {
return emptyList()
}
val listType = object : TypeToken<List<UserData.OrderItem>>() {}.type
val gson = Gson()
return gson.fromJson(data, listType)
}
@TypeConverter
fun orderObjectListToString(orderList: List<UserData.OrderItem>): String {
if (orderList.isEmpty()) {
return ""
}
val gson = Gson()
val listType = object : TypeToken<List<UserData.OrderItem>>() {}.type
return gson.toJson(orderList, listType)
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/ui/loginSignup/SignupFragmentTest.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import androidx.fragment.app.testing.FragmentScenario
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.testing.TestNavHostController
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.intent.Intents
import androidx.test.espresso.intent.Intents.intended
import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import androidx.test.platform.app.InstrumentationRegistry
import com.vishalgaur.shoppingapp.EMAIL_ERROR_TEXT
import com.vishalgaur.shoppingapp.MOB_ERROR_TEXT
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.clickClickableSpan
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import org.hamcrest.Matchers.`is`
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class SignupFragmentTest {
private lateinit var signUpScenario: FragmentScenario<SignupFragment>
private lateinit var navController: NavController
private lateinit var sessionManager: ShoppingAppSessionManager
@Before
fun setUp() {
sessionManager = ShoppingAppSessionManager(ApplicationProvider.getApplicationContext())
sessionManager.logoutFromSession()
signUpScenario = launchFragmentInContainer(themeResId = R.style.Theme_ShoppingApp)
navController = TestNavHostController(ApplicationProvider.getApplicationContext())
runOnUiThread {
navController.setGraph(R.navigation.signup_nav_graph)
signUpScenario.onFragment {
Navigation.setViewNavController(it.requireView(), navController)
}
}
}
@Test
fun useAppContext() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.vishalgaur.shoppingapp", context.packageName)
}
@Test
fun userCanEnterName() {
insertInNameEditText("<NAME> ")
}
@Test
fun userCanEnterMobile() {
insertInMobileEditText("8976527465")
}
@Test
fun userCanEnterEmail() {
insertInEmailEditText(" <EMAIL>")
}
@Test
fun userCanEnterPassword() {
insertInPwdEditText("<PASSWORD>")
}
@Test
fun userCanEnterInCnfPassword() {
insertInCnfPwdEditText("<PASSWORD>")
}
@Test
fun userCanClickTermsSwitch() {
clickTermsSwitch()
}
@Test
fun userCanClickSellerSwitch() {
clickSellerSwitch()
}
@Test
fun userCanClickSignUp() {
clickSignUpButton()
}
@Test
fun userCanClickLogInText() {
clickLoginText()
}
@Test
fun onLoginClick_navigateToLoginFragment() {
clickLoginText()
assertEquals(navController.currentDestination?.id, R.id.LoginFragment)
}
@Test
fun onSignUp_emptyForm_showsError() {
clickSignUpButton()
onView(withId(R.id.signup_error_text_view)).check(matches(isDisplayed()))
}
@Test
fun onSignUp_invalidEmail_showsEmailError() {
insertInNameEditText("<NAME> ")
insertInMobileEditText("8976527465 ")
insertInEmailEditText(" <EMAIL>")
insertInPwdEditText("<PASSWORD>")
insertInCnfPwdEditText("<PASSWORD>")
clickTermsSwitch()
clickSignUpButton()
onView(withId(R.id.signup_email_edit_text)).check(matches(hasErrorText(`is`(EMAIL_ERROR_TEXT))))
}
@Test
fun onSignUp_invalidMobile_showsMobileError() {
insertInNameEditText("<NAME> ")
insertInMobileEditText("86527465 ")
insertInEmailEditText(" <EMAIL>")
insertInPwdEditText("<PASSWORD>")
insertInCnfPwdEditText("<PASSWORD>")
clickTermsSwitch()
clickSignUpButton()
onView(withId(R.id.signup_mobile_edit_text)).check(matches(hasErrorText(`is`(MOB_ERROR_TEXT))))
}
@Test
fun onSignUp_notAcceptedTerms_showsError() {
insertInNameEditText("<NAME> ")
insertInMobileEditText("8652744565 ")
insertInEmailEditText(" <EMAIL>")
insertInPwdEditText("<PASSWORD>")
insertInCnfPwdEditText("<PASSWORD>")
clickSignUpButton()
onView(withId(R.id.signup_error_text_view)).check(matches(withText("Accept the Terms.")))
}
@Test
fun onSignUp_notSamePasswords_showsError() {
insertInNameEditText("<NAME> ")
insertInMobileEditText("8652744565 ")
insertInEmailEditText(" <EMAIL>")
insertInPwdEditText("<PASSWORD>")
insertInCnfPwdEditText("<PASSWORD>")
clickTermsSwitch()
clickSignUpButton()
onView(withId(R.id.signup_error_text_view)).check(matches(withText("Both passwords are not same!")))
}
@Test
fun onSignUp_validForm_showsNoError() {
Intents.init()
insertInNameEditText("<NAME> ")
insertInMobileEditText("8652744565 ")
insertInEmailEditText(" <EMAIL>")
insertInPwdEditText("<PASSWORD>")
insertInCnfPwdEditText("<PASSWORD>")
clickTermsSwitch()
clickSignUpButton()
intended(hasComponent(OtpActivity::class.java.name))
}
private fun insertInNameEditText(name: String) =
onView(withId(R.id.signup_name_edit_text)).perform(scrollTo(), clearText(), typeText(name))
private fun insertInMobileEditText(phone: String) =
onView(withId(R.id.signup_mobile_edit_text)).perform(
scrollTo(),
clearText(),
typeText(phone)
)
private fun insertInEmailEditText(email: String) =
onView(withId(R.id.signup_email_edit_text)).perform(
scrollTo(),
clearText(),
typeText(email)
)
private fun insertInPwdEditText(pwd: String) =
onView(withId(R.id.signup_password_edit_text)).perform(
scrollTo(),
clearText(),
typeText(pwd)
)
private fun insertInCnfPwdEditText(pwd2: String) =
onView(withId(R.id.signup_cnf_password_edit_text)).perform(
scrollTo(),
clearText(),
typeText(pwd2)
)
private fun clickTermsSwitch() =
onView(withId(R.id.signup_policy_switch)).perform(scrollTo(), click())
private fun clickSellerSwitch() =
onView(withId(R.id.signup_seller_switch)).perform(scrollTo(), click())
private fun clickSignUpButton() =
onView(withId(R.id.signup_signup_btn)).perform(scrollTo(), click())
private fun clickLoginText() =
onView(withId(R.id.signup_login_text_view)).perform(
scrollTo(),
clickClickableSpan("Log In")
)
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/AddressAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.databinding.LayoutAddressCardBinding
import com.vishalgaur.shoppingapp.ui.getCompleteAddress
private const val TAG = "AddressAdapter"
class AddressAdapter(
private val context: Context,
addresses: List<UserData.Address>,
private val isSelect: Boolean
) :
RecyclerView.Adapter<AddressAdapter.ViewHolder>() {
lateinit var onClickListener: OnClickListener
var data: List<UserData.Address> = addresses
var lastCheckedAddress: String? = null
private var lastCheckedCard: MaterialCardView? = null
var selectedAddressPos = -1
inner class ViewHolder(private var binding: LayoutAddressCardBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(address: UserData.Address, position: Int) {
binding.addressCard.isChecked = position == selectedAddressPos
binding.addressPersonNameTv.text =
context.getString(R.string.person_name, address.fName, address.lName)
binding.addressCompleteAddressTv.text = getCompleteAddress(address)
binding.addressMobileTv.text = address.phoneNumber
if (isSelect) {
binding.addressCard.setOnClickListener {
onCardClick(position, address.addressId, it as MaterialCardView)
}
}
binding.addressEditBtn.setOnClickListener {
onClickListener.onEditClick(address.addressId)
}
binding.addressDeleteBtn.setOnClickListener {
onClickListener.onDeleteClick(address.addressId)
notifyDataSetChanged()
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutAddressCardBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position], position)
}
override fun getItemCount(): Int = data.size
interface OnClickListener {
fun onEditClick(addressId: String)
fun onDeleteClick(addressId: String)
}
private fun onCardClick(position: Int, addressTd: String, card: MaterialCardView) {
if (addressTd != lastCheckedAddress) {
card.apply {
strokeColor = context.getColor(R.color.blue_accent_300)
isChecked = true
strokeWidth = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
2F,
resources.displayMetrics
).toInt()
}
lastCheckedCard?.apply {
strokeColor = context.getColor(R.color.light_gray)
isChecked = false
strokeWidth = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
1F,
resources.displayMetrics
).toInt()
}
lastCheckedAddress = addressTd
lastCheckedCard = card
selectedAddressPos = position
Log.d(TAG, "onCardClick: selected address = $addressTd")
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/HomeViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.util.Log
import androidx.lifecycle.*
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.time.Month
import java.util.*
private const val TAG = "HomeViewModel"
class HomeViewModel(application: Application) : AndroidViewModel(application) {
private val productsRepository =
(application.applicationContext as ShoppingApplication).productsRepository
private val authRepository =
(application.applicationContext as ShoppingApplication).authRepository
private val sessionManager = ShoppingAppSessionManager(application.applicationContext)
private val currentUser = sessionManager.getUserIdFromSession()
val isUserASeller = sessionManager.isUserSeller()
private var _products = MutableLiveData<List<Product>>()
val products: LiveData<List<Product>> get() = _products
private lateinit var _allProducts: MutableLiveData<List<Product>>
val allProducts: LiveData<List<Product>> get() = _allProducts
private var _userProducts = MutableLiveData<List<Product>>()
val userProducts: LiveData<List<Product>> get() = _userProducts
private var _userOrders = MutableLiveData<List<UserData.OrderItem>>()
val userOrders: LiveData<List<UserData.OrderItem>> get() = _userOrders
private var _userAddresses = MutableLiveData<List<UserData.Address>>()
val userAddresses: LiveData<List<UserData.Address>> get() = _userAddresses
private var _selectedOrder = MutableLiveData<UserData.OrderItem?>()
val selectedOrder: LiveData<UserData.OrderItem?> get() = _selectedOrder
private var _orderProducts = MutableLiveData<List<Product>>()
val orderProducts: LiveData<List<Product>> get() = _orderProducts
private var _likedProducts = MutableLiveData<List<Product>>()
val likedProducts: LiveData<List<Product>> get() = _likedProducts
private var _userLikes = MutableLiveData<List<String>>()
val userLikes: LiveData<List<String>> get() = _userLikes
private var _filterCategory = MutableLiveData("All")
val filterCategory: LiveData<String> get() = _filterCategory
private val _storeDataStatus = MutableLiveData<StoreDataStatus>()
val storeDataStatus: LiveData<StoreDataStatus> get() = _storeDataStatus
private val _dataStatus = MutableLiveData<StoreDataStatus>()
val dataStatus: LiveData<StoreDataStatus> get() = _dataStatus
private val _userData = MutableLiveData<UserData?>()
val userData: LiveData<UserData?> get() = _userData
init {
viewModelScope.launch {
authRepository.hardRefreshUserData()
getUserLikes()
}
if (isUserASeller)
getProductsByOwner()
else
getProducts()
}
fun setDataLoaded() {
_storeDataStatus.value = StoreDataStatus.DONE
}
fun isProductLiked(productId: String): Boolean {
return _userLikes.value?.contains(productId) == true
}
fun toggleLikeByProductId(productId: String) {
Log.d(TAG, "Toggling Like")
viewModelScope.launch {
val isLiked = isProductLiked(productId)
val allLikes = _userLikes.value?.toMutableList() ?: mutableListOf()
val deferredRes = async {
if (isLiked) {
authRepository.removeProductFromLikes(productId, currentUser!!)
} else {
authRepository.insertProductToLikes(productId, currentUser!!)
}
}
val res = deferredRes.await()
if (res is Success) {
if (isLiked) {
allLikes.remove(productId)
} else {
allLikes.add(productId)
}
_userLikes.value = allLikes
val proList = _likedProducts.value?.toMutableList() ?: mutableListOf()
val pro = proList.find { it.productId == productId }
if (pro != null) {
proList.remove(pro)
}
_likedProducts.value = proList
Log.d(TAG, "onToggleLike: Success")
} else {
if (res is Error) {
Log.d(TAG, "onToggleLike: Error, ${res.exception}")
}
}
}
}
fun isProductInCart(productId: String): Boolean {
return false
}
fun toggleProductInCart(product: Product) {
}
fun setDataLoading() {
_dataStatus.value = StoreDataStatus.LOADING
}
private fun getProducts() {
_allProducts = Transformations.switchMap(productsRepository.observeProducts()) {
getProductsLiveData(it)
} as MutableLiveData<List<Product>>
viewModelScope.launch {
_storeDataStatus.value = StoreDataStatus.LOADING
val res = async { productsRepository.refreshProducts() }
res.await()
Log.d(TAG, "getAllProducts: status = ${_storeDataStatus.value}")
}
}
fun getUserLikes() {
viewModelScope.launch {
val res = authRepository.getLikesByUserId(currentUser!!)
if (res is Success) {
val data = res.data ?: emptyList()
if (data[0] != "") {
_userLikes.value = data
} else {
_userLikes.value = emptyList()
}
Log.d(TAG, "Getting Likes: Success")
} else {
_userLikes.value = emptyList()
if (res is Error)
Log.d(TAG, "Getting Likes: Error, ${res.exception}")
}
}
}
fun getLikedProducts() {
val res: List<Product> = if (_userLikes.value != null) {
val allLikes = _userLikes.value ?: emptyList()
if (!allLikes.isNullOrEmpty()) {
Log.d(TAG, "alllikes = ${allLikes.size}")
_dataStatus.value = StoreDataStatus.DONE
allLikes.map { proId ->
_allProducts.value?.find { it.productId == proId } ?: Product()
}
} else {
_dataStatus.value = StoreDataStatus.ERROR
emptyList()
}
} else {
_dataStatus.value = StoreDataStatus.ERROR
emptyList()
}
_likedProducts.value = res
}
private fun getProductsLiveData(result: Result<List<Product>?>?): LiveData<List<Product>> {
val res = MutableLiveData<List<Product>>()
if (result is Success) {
Log.d(TAG, "result is success")
_storeDataStatus.value = StoreDataStatus.DONE
res.value = result.data ?: emptyList()
} else {
Log.d(TAG, "result is not success")
res.value = emptyList()
_storeDataStatus.value = StoreDataStatus.ERROR
if (result is Error)
Log.d(TAG, "getProductsLiveData: Error Occurred: ${result.exception}")
}
return res
}
private fun getProductsByOwner() {
_allProducts =
Transformations.switchMap(productsRepository.observeProductsByOwner(currentUser!!)) {
Log.d(TAG, it.toString())
getProductsLiveData(it)
} as MutableLiveData<List<Product>>
viewModelScope.launch {
_storeDataStatus.value = StoreDataStatus.LOADING
val res = async { productsRepository.refreshProducts() }
res.await()
Log.d(TAG, "getProductsByOwner: status = ${_storeDataStatus.value}")
}
}
fun refreshProducts() {
getProducts()
}
fun filterBySearch(queryText: String) {
filterProducts(_filterCategory.value!!)
_products.value = _products.value?.filter { product ->
product.name.contains(queryText, true) or
((queryText.toDoubleOrNull() ?: 0.0).compareTo(product.price) == 0)
}
}
fun filterProducts(filterType: String) {
Log.d(TAG, "filterType is $filterType")
_filterCategory.value = filterType
_products.value = when (filterType) {
"None" -> emptyList()
"All" -> _allProducts.value
else -> _allProducts.value?.filter { product ->
product.category == filterType
}
}
}
fun deleteProduct(productId: String) {
viewModelScope.launch {
val delRes = async { productsRepository.deleteProductById(productId) }
when (val res = delRes.await()) {
is Success -> Log.d(TAG, "onDelete: Success")
is Error -> Log.d(TAG, "onDelete: Error, ${res.exception}")
else -> Log.d(TAG, "onDelete: Some error occurred!")
}
}
}
fun signOut() {
viewModelScope.launch {
val deferredRes = async { authRepository.signOut() }
deferredRes.await()
}
}
fun getAllOrders() {
viewModelScope.launch {
_storeDataStatus.value = StoreDataStatus.LOADING
val deferredRes = async { authRepository.getOrdersByUserId(currentUser!!) }
val res = deferredRes.await()
if (res is Success) {
_userOrders.value = res.data ?: emptyList()
_storeDataStatus.value = StoreDataStatus.DONE
Log.d(TAG, "Getting Orders: Success")
} else {
_userOrders.value = emptyList()
_storeDataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "Getting Orders: Error, ${res.exception}")
}
}
}
fun getOrderDetailsByOrderId(orderId: String) {
viewModelScope.launch {
_storeDataStatus.value = StoreDataStatus.LOADING
if (_userOrders.value != null) {
val orderData = _userOrders.value!!.find { it.orderId == orderId }
if (orderData != null) {
_selectedOrder.value = orderData
_orderProducts.value =
orderData.items.map {
_allProducts.value?.find { pro -> pro.productId == it.productId }
?: Product()
}
_storeDataStatus.value = StoreDataStatus.DONE
} else {
_selectedOrder.value = null
_storeDataStatus.value = StoreDataStatus.ERROR
}
}
}
}
fun onSetStatusOfOrder(orderId: String, status: String) {
val currDate = Calendar.getInstance()
val dateString =
"${Month.values()[(currDate.get(Calendar.MONTH))].name} ${
currDate.get(Calendar.DAY_OF_MONTH)
}, ${currDate.get(Calendar.YEAR)}"
Log.d(TAG, "Selected Status is $status ON $dateString")
setStatusOfOrder(orderId, "$status ON $dateString")
}
private fun setStatusOfOrder(orderId: String, statusString: String) {
viewModelScope.launch {
_storeDataStatus.value = StoreDataStatus.LOADING
val deferredRes = async {
authRepository.setStatusOfOrder(orderId, currentUser!!, statusString)
}
val res = deferredRes.await()
if (res is Success) {
val orderData = _selectedOrder.value
orderData?.status = statusString
_selectedOrder.value = orderData
getOrderDetailsByOrderId(orderId)
} else {
_storeDataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "Error updating status, ${res.exception}")
}
}
}
fun getUserAddresses() {
Log.d(TAG, "Getting Addresses")
_dataStatus.value = StoreDataStatus.LOADING
viewModelScope.launch {
val res = authRepository.getAddressesByUserId(currentUser!!)
if (res is Success) {
_userAddresses.value = res.data ?: emptyList()
_dataStatus.value = StoreDataStatus.DONE
Log.d(TAG, "Getting Addresses: Success")
} else {
_userAddresses.value = emptyList()
_dataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "Getting Addresses: Error Occurred, ${res.exception.message}")
}
}
}
fun deleteAddress(addressId: String) {
viewModelScope.launch {
val delRes = async { authRepository.deleteAddressById(addressId, currentUser!!) }
when (val res = delRes.await()) {
is Success -> {
Log.d(TAG, "onDeleteAddress: Success")
val addresses = _userAddresses.value?.toMutableList()
addresses?.let {
val pos =
addresses.indexOfFirst { address -> address.addressId == addressId }
if (pos >= 0)
it.removeAt(pos)
_userAddresses.value = it
}
}
is Error -> Log.d(TAG, "onDeleteAddress: Error, ${res.exception}")
else -> Log.d(TAG, "onDeleteAddress: Some error occurred!")
}
}
}
fun getUserData() {
viewModelScope.launch {
_dataStatus.value = StoreDataStatus.LOADING
val deferredRes = async { authRepository.getUserData(currentUser!!) }
val res = deferredRes.await()
if (res is Success) {
val uData = res.data
_userData.value = uData
_dataStatus.value = StoreDataStatus.DONE
} else {
_dataStatus.value = StoreDataStatus.ERROR
_userData.value = null
}
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/AuthViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.vishalgaur.shoppingapp.*
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.LogInErrors
import com.vishalgaur.shoppingapp.data.utils.SignUpErrors
import com.vishalgaur.shoppingapp.data.utils.UserType
import com.vishalgaur.shoppingapp.ui.LoginViewErrors
import com.vishalgaur.shoppingapp.ui.SignUpViewErrors
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
private const val TAG = "AuthViewModel"
class AuthViewModel(application: Application) : AndroidViewModel(application) {
private val authRepository = (application as ShoppingApplication).authRepository
private val productsRepository = (application as ShoppingApplication).productsRepository
private val _userData = MutableLiveData<UserData>()
val userData: LiveData<UserData> get() = _userData
private val _signErrorStatus = MutableLiveData<SignUpErrors?>()
val signErrorStatus: LiveData<SignUpErrors?> get() = _signErrorStatus
private val _errorStatus = MutableLiveData<SignUpViewErrors>()
val errorStatus: LiveData<SignUpViewErrors> get() = _errorStatus
private val _errorStatusLoginFragment = MutableLiveData<LoginViewErrors>()
val errorStatusLoginFragment: LiveData<LoginViewErrors> get() = _errorStatusLoginFragment
private val _loginErrorStatus = MutableLiveData<LogInErrors?>()
val loginErrorStatus: LiveData<LogInErrors?> get() = _loginErrorStatus
init {
_errorStatus.value = SignUpViewErrors.NONE
_errorStatusLoginFragment.value = LoginViewErrors.NONE
refreshStatus()
}
private fun refreshStatus() {
viewModelScope.launch {
getCurrUser()
productsRepository.refreshProducts()
}
}
fun signUpSubmitData(
name: String,
mobile: String,
email: String,
pwd1: String,
pwd2: String,
isAccepted: Boolean,
isSeller: Boolean
) {
if (name.isBlank() || mobile.isBlank() || email.isBlank() || pwd1.isBlank() || pwd2.isBlank()) {
_errorStatus.value = SignUpViewErrors.ERR_EMPTY
} else {
if (pwd1 != pwd2) {
_errorStatus.value = SignUpViewErrors.ERR_PWD12NS
} else {
if (!isAccepted) {
_errorStatus.value = SignUpViewErrors.ERR_NOT_ACC
} else {
var err = ERR_INIT
if (!isEmailValid(email)) {
err += ERR_EMAIL
}
if (!isPhoneValid(mobile)) {
err += ERR_MOBILE
}
when (err) {
ERR_INIT -> {
_errorStatus.value = SignUpViewErrors.NONE
val uId = getRandomString(32, "91" + mobile.trim(), 6)
val newData =
UserData(
uId,
name.trim(),
"+91" + mobile.trim(),
email.trim(),
pwd1.trim(),
ArrayList(),
ArrayList(),
ArrayList(),
ArrayList(),
if (isSeller) UserType.SELLER.name else UserType.CUSTOMER.name
)
_userData.value = newData
checkUniqueUser(newData)
}
(ERR_INIT + ERR_EMAIL) -> _errorStatus.value = SignUpViewErrors.ERR_EMAIL
(ERR_INIT + ERR_MOBILE) -> _errorStatus.value = SignUpViewErrors.ERR_MOBILE
(ERR_INIT + ERR_EMAIL + ERR_MOBILE) -> _errorStatus.value =
SignUpViewErrors.ERR_EMAIL_MOBILE
}
}
}
}
}
private fun checkUniqueUser(uData: UserData) {
viewModelScope.launch {
val res = async { authRepository.checkEmailAndMobile(uData.email, uData.mobile, getApplication<ShoppingApplication>().applicationContext) }
_signErrorStatus.value = res.await()
}
}
fun loginSubmitData(mobile: String, password: String) {
if (mobile.isBlank() || password.isBlank()) {
_errorStatusLoginFragment.value = LoginViewErrors.ERR_EMPTY
} else {
if (!isPhoneValid(mobile)) {
_errorStatusLoginFragment.value = LoginViewErrors.ERR_MOBILE
} else {
_errorStatusLoginFragment.value = LoginViewErrors.NONE
logIn("+91" + mobile.trim(), password)
}
}
}
private fun logIn(phoneNumber: String, pwd: String) {
viewModelScope.launch {
val res = async { authRepository.checkLogin(phoneNumber, pwd) }
_userData.value = res.await()
if (_userData.value != null) {
_loginErrorStatus.value = LogInErrors.NONE
} else {
_loginErrorStatus.value = LogInErrors.LERR
}
}
}
private suspend fun getCurrUser() {
Log.d(TAG, "refreshing data...")
authRepository.refreshData()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/MainActivity.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.databinding.ActivityMainBinding
private const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate starts")
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
// Bottom Navigation
setUpNav()
}
private fun setUpNav() {
val navFragment =
supportFragmentManager.findFragmentById(R.id.home_nav_host_fragment) as NavHostFragment
NavigationUI.setupWithNavController(binding.homeBottomNavigation, navFragment.navController)
navFragment.navController.addOnDestinationChangedListener { _, destination, _ ->
when (destination.id) {
R.id.homeFragment -> setBottomNavVisibility(View.VISIBLE)
R.id.cartFragment -> setBottomNavVisibility(View.VISIBLE)
R.id.accountFragment -> setBottomNavVisibility(View.VISIBLE)
R.id.ordersFragment -> setBottomNavVisibility(View.VISIBLE)
R.id.orderSuccessFragment -> setBottomNavVisibility(View.VISIBLE)
else -> setBottomNavVisibility(View.GONE)
}
}
val sessionManager = ShoppingAppSessionManager(this.applicationContext)
if (sessionManager.isUserSeller()) {
binding.homeBottomNavigation.menu.removeItem(R.id.cartFragment)
}else {
binding.homeBottomNavigation.menu.removeItem(R.id.ordersFragment)
}
}
private fun setBottomNavVisibility(visibility: Int) {
binding.homeBottomNavigation.visibility = visibility
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ShoppingApplication.kt
package com.vishalgaur.shoppingapp
import android.app.Application
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
class ShoppingApplication : Application() {
val authRepository: AuthRepoInterface
get() = ServiceLocator.provideAuthRepository(this)
val productsRepository: ProductsRepoInterface
get() = ServiceLocator.provideProductsRepository(this)
override fun onCreate() {
super.onCreate()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/LikedProductAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.databinding.ProductsListItemBinding
import com.vishalgaur.shoppingapp.getOfferPercentage
class LikedProductAdapter(proList: List<Product>, private val context: Context) :
RecyclerView.Adapter<LikedProductAdapter.ViewHolder>() {
var data = proList
lateinit var onClickListener: OnClickListener
inner class ViewHolder(private val binding: ProductsListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(productData: Product) {
binding.productCard.setOnClickListener {
onClickListener.onClick(productData)
}
binding.productNameTv.text = productData.name
binding.productPriceTv.text =
context.getString(R.string.pro_details_price_value, productData.price.toString())
binding.productRatingBar.rating = productData.rating.toFloat()
binding.productActualPriceTv.apply {
paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
text = context.getString(
R.string.pro_details_actual_strike_value,
productData.mrp.toString()
)
}
binding.productOfferValueTv.text = context.getString(
R.string.pro_offer_precent_text,
getOfferPercentage(productData.mrp, productData.price).toString()
)
if (productData.images.isNotEmpty()) {
val imgUrl = productData.images[0].toUri().buildUpon().scheme("https").build()
Glide.with(context)
.asBitmap()
.load(imgUrl)
.into(binding.productImageView)
binding.productImageView.clipToOutline = true
}
//hiding unnecessary button
binding.productAddToCartButton.visibility = View.GONE
binding.productDeleteButton.visibility = View.GONE
binding.productLikeCheckbox.visibility = View.GONE
// setting edit button as delete button
binding.productEditButton.setImageResource(R.drawable.ic_delete_24)
binding.productEditButton.setOnClickListener {
onClickListener.onDeleteClick(productData.productId)
notifyDataSetChanged()
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ProductsListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount() = data.size
interface OnClickListener {
fun onClick(productData: Product)
fun onDeleteClick(productId: String)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/local/ProductsLocalDataSource.kt
package com.vishalgaur.shoppingapp.data.source.local
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.*
import com.vishalgaur.shoppingapp.data.source.ProductDataSource
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class ProductsLocalDataSource internal constructor(
private val productsDao: ProductsDao,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : ProductDataSource {
override fun observeProducts(): LiveData<Result<List<Product>>?> {
return try {
Transformations.map(productsDao.observeProducts()) {
Success(it)
}
} catch (e: Exception) {
Transformations.map(MutableLiveData(e)) {
Error(e)
}
}
}
override fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?> {
return try {
Transformations.map(productsDao.observeProductsByOwner(ownerId)) {
Success(it)
}
} catch (e: Exception) {
Transformations.map(MutableLiveData(e)) {
Error(e)
}
}
}
override suspend fun getAllProducts(): Result<List<Product>> = withContext(ioDispatcher) {
return@withContext try {
Success(productsDao.getAllProducts())
} catch (e: Exception) {
Error(e)
}
}
override suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>> =
withContext(ioDispatcher) {
return@withContext try {
Success(productsDao.getProductsByOwnerId(ownerId))
} catch (e: Exception) {
Error(e)
}
}
override suspend fun getProductById(productId: String): Result<Product> =
withContext(ioDispatcher) {
try {
val product = productsDao.getProductById(productId)
if (product != null) {
return@withContext Success(product)
} else {
return@withContext Error(Exception("Product Not Found!"))
}
} catch (e: Exception) {
return@withContext Error(e)
}
}
override suspend fun insertProduct(newProduct: Product) = withContext(ioDispatcher) {
productsDao.insert(newProduct)
}
override suspend fun updateProduct(proData: Product) = withContext(ioDispatcher) {
productsDao.insert(proData)
}
override suspend fun insertMultipleProducts(data: List<Product>) = withContext(ioDispatcher) {
productsDao.insertListOfProducts(data)
}
override suspend fun deleteProduct(productId: String): Unit = withContext(ioDispatcher) {
productsDao.deleteProductById(productId)
}
override suspend fun deleteAllProducts() = withContext(ioDispatcher) {
productsDao.deleteAllProducts()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/ProductDataSource.kt
package com.vishalgaur.shoppingapp.data.source
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
interface ProductDataSource {
fun observeProducts(): LiveData<Result<List<Product>>?>
suspend fun getAllProducts(): Result<List<Product>>
suspend fun refreshProducts() {}
suspend fun getProductById(productId: String): Result<Product>
suspend fun insertProduct(newProduct: Product)
suspend fun updateProduct(proData: Product)
fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?> {
return MutableLiveData()
}
suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>> {
return Result.Success(emptyList())
}
suspend fun uploadImage(uri: Uri, fileName: String): Uri? {
return null
}
fun revertUpload(fileName: String) {}
fun deleteImage(imgUrl: String) {}
suspend fun deleteProduct(productId: String)
suspend fun deleteAllProducts() {}
suspend fun insertMultipleProducts(data: List<Product>) {}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/ProfileFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.databinding.FragmentProfileBinding
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
class ProfileFragment : Fragment() {
private lateinit var binding: FragmentProfileBinding
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentProfileBinding.inflate(layoutInflater)
binding.profileTopAppBar.topAppBar.title = getString(R.string.account_profile_label)
binding.profileTopAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getUserData()
setViews()
}
private fun setViews() {
viewModel.userData.observe(viewLifecycleOwner) {
if (it != null) {
binding.profileNameTv.text = it.name
binding.profileEmailTv.text = it.email
binding.profileMobileTv.text = it.mobile
}
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/local/ProductsDao.kt
package com.vishalgaur.shoppingapp.data.source.local
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.vishalgaur.shoppingapp.data.Product
@Dao
interface ProductsDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(product: Product)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertListOfProducts(products: List<Product>)
@Query("SELECT * FROM products")
suspend fun getAllProducts(): List<Product>
@Query("SELECT * FROM products")
fun observeProducts(): LiveData<List<Product>>
@Query("SELECT * FROM products WHERE owner = :ownerId")
fun observeProductsByOwner(ownerId: String): LiveData<List<Product>>
@Query("SELECT * FROM products WHERE productId = :proId")
suspend fun getProductById(proId: String): Product?
@Query("SELECT * FROM products WHERE owner = :ownerId")
suspend fun getProductsByOwnerId(ownerId: String): List<Product>
@Query("DELETE FROM products WHERE productId = :proId")
suspend fun deleteProductById(proId: String): Int
@Query("DELETE FROM products")
suspend fun deleteAllProducts()
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/PayByAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.annotation.SuppressLint
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.card.MaterialCardView
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.databinding.LayoutListItemBinding
private const val TAG = "PayByAdapter"
class PayByAdapter(private val data: List<String>) :
RecyclerView.Adapter<PayByAdapter.ViewHolder>() {
var lastCheckedMethod: String? = null
private var lastCheckedCard: MaterialCardView? = null
private var selectedMethodPos = -1
inner class ViewHolder(binding: LayoutListItemBinding) :
RecyclerView.ViewHolder(binding.root) {
val textView = binding.itemTitleTextView
val cardView = binding.itemCard
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
@SuppressLint("ResourceAsColor")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val title = data[position]
holder.apply {
textView.text = title
cardView.setOnClickListener {
onCardClick(position, data[position], it as MaterialCardView)
}
}
}
override fun getItemCount() = data.size
private fun onCardClick(position: Int, method: String, cardView: MaterialCardView) {
if (method != lastCheckedMethod) {
cardView.apply {
strokeColor = context.getColor(R.color.blue_accent_300)
isChecked = true
strokeWidth = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
2F,
resources.displayMetrics
).toInt()
}
lastCheckedCard?.apply {
strokeColor = context.getColor(R.color.light_gray)
isChecked = false
strokeWidth = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
1F,
resources.displayMetrics
).toInt()
}
lastCheckedCard = cardView
lastCheckedMethod = method
selectedMethodPos = position
Log.d(TAG, "onSelectMethod: Selected Method = $lastCheckedMethod")
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/ProductImagesAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.net.toUri
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.vishalgaur.shoppingapp.databinding.ImagesItemBinding
class ProductImagesAdapter(private val context: Context, private val images: List<String>) :
RecyclerView.Adapter<ProductImagesAdapter.ViewHolder>() {
class ViewHolder(binding: ImagesItemBinding) : RecyclerView.ViewHolder(binding.root) {
val imageView = binding.rcImageView
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ImagesItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val imageUrl = images[position]
val imgUrl = imageUrl.toUri().buildUpon().scheme("https").build()
Glide.with(context)
.asBitmap()
.load(imgUrl)
.into(holder.imageView)
}
override fun getItemCount(): Int = images.size
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/viewModels/OrderViewModelTest.kt
package com.vishalgaur.shoppingapp.viewModels
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.ServiceLocator
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.FakeAuthRepository
import com.vishalgaur.shoppingapp.data.source.FakeProductsRepository
import com.vishalgaur.shoppingapp.data.source.repository.AuthRepoInterface
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.getOrAwaitValue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.Matchers.*
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class OrderViewModelTest {
private lateinit var orderViewModel: OrderViewModel
private lateinit var productsRepository: ProductsRepoInterface
private lateinit var authRepository: AuthRepoInterface
val user = UserData(
"sdjm43892yfh948ehod",
"Vishal",
"+919999988888",
"<EMAIL>",
"dh94328hd",
ArrayList(),
ArrayList(),
ArrayList()
)
val address = UserData.Address(
"add-id-121",
"adg",
"shgd",
"IN",
"sfhg45eyh",
"",
"kanpuit",
"up",
"309890",
"9999988558"
)
val item1 = UserData.CartItem(
"item2123",
"pro123",
"owner23",
1,
"Red",
10
)
val item2 = UserData.CartItem(
"item2123456347",
"pro12345",
"owner23",
1,
"Blue",
9
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
productsRepository = FakeProductsRepository()
val context = ApplicationProvider.getApplicationContext<ShoppingApplication>()
val sessionManager = ShoppingAppSessionManager(context)
authRepository = FakeAuthRepository(sessionManager)
authRepository.login(user, true)
ServiceLocator.productsRepository = productsRepository
ServiceLocator.authRepository = authRepository
orderViewModel = OrderViewModel(context)
}
@After
fun cleanUp() = runBlockingTest {
ServiceLocator.resetRepository()
}
@Test
fun getCartItems_loadsData() = runBlocking {
orderViewModel.getCartItems()
delay(200)
val result = orderViewModel.dataStatus.getOrAwaitValue()
assertThat(result, `is`(StoreDataStatus.DONE))
}
@Test
fun getAddresses_noAddress_loadsData() = runBlocking {
orderViewModel.getUserAddresses()
delay(200)
val result = orderViewModel.dataStatus.getOrAwaitValue()
assertThat(result, `is`(StoreDataStatus.DONE))
val resAdd = orderViewModel.userAddresses.getOrAwaitValue()
assertThat(resAdd.size, `is`(0))
}
@Test
fun getAddresses_hasAddress_loadsData() = runBlocking {
authRepository.insertAddress(address, user.userId)
delay(100)
orderViewModel.getUserAddresses()
delay(100)
val result = orderViewModel.dataStatus.getOrAwaitValue()
assertThat(result, `is`(StoreDataStatus.DONE))
val resAdd = orderViewModel.userAddresses.getOrAwaitValue()
assertThat(resAdd.size, `is`(1))
}
@Test
fun deleteAddress_deletesAddress() = runBlocking{
authRepository.insertAddress(address, user.userId)
delay(100)
orderViewModel.getUserAddresses()
delay(100)
val resAdd = orderViewModel.userAddresses.getOrAwaitValue()
assertThat(resAdd.size, `is`(1))
orderViewModel.deleteAddress(address.addressId)
delay(100)
val resAdd2 = orderViewModel.userAddresses.getOrAwaitValue()
assertThat(resAdd2.size, `is`(0))
}
@Test
fun getItemsPriceTotal_returnsTotal() {
runBlocking {
authRepository.insertCartItemByUserId(item1, user.userId)
delay(100)
val result = orderViewModel.getItemsPriceTotal()
assertThat(result, `is`(0.0))
}
}
@Test
fun toggleLike() {
runBlocking {
val res1 = orderViewModel.userLikes.getOrAwaitValue()
orderViewModel.toggleLikeProduct("pro-if2r3")
delay(100)
val res2 = orderViewModel.userLikes.getOrAwaitValue()
assertThat(res1.size, not(res2.size))
}
}
@Test
fun setQuantity_setsQuantity() = runBlocking {
authRepository.insertCartItemByUserId(item1, user.userId)
delay(100)
val res1 = orderViewModel.cartItems.getOrAwaitValue().find { it.itemId == item1.itemId }
val size1 = res1?.quantity ?: 0
orderViewModel.setQuantityOfItem(item1.itemId, 1)
delay(100)
val res2 = orderViewModel.cartItems.getOrAwaitValue().find { it.itemId == item1.itemId }
val size2 = res2?.quantity ?: 0
assertThat(size1, `is`(1))
assertThat(size2, `is`(2))
}
@Test
fun deleteItemFromCart_deletesItem() = runBlocking {
authRepository.insertCartItemByUserId(item1, user.userId)
delay(100)
val res1 = orderViewModel.cartItems.getOrAwaitValue().find { it.itemId == item1.itemId }
assertThat(res1, `is`(notNullValue()))
orderViewModel.deleteItemFromCart(item1.itemId)
delay(100)
val res2 = orderViewModel.cartItems.getOrAwaitValue().find { it.itemId == item1.itemId }
assertThat(res2, `is`(nullValue()))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/OrderDetailsFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.OrderStatus
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentOrderDetailsBinding
import com.vishalgaur.shoppingapp.ui.getCompleteAddress
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
import java.time.Month
import java.util.*
class OrderDetailsFragment : Fragment() {
private lateinit var binding: FragmentOrderDetailsBinding
private val viewModel: HomeViewModel by activityViewModels()
private lateinit var orderId: String
private lateinit var productsAdapter: OrderProductsAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentOrderDetailsBinding.inflate(layoutInflater)
orderId = arguments?.getString("orderId").toString()
viewModel.getOrderDetailsByOrderId(orderId)
setViews()
setObservers()
return binding.root
}
private fun setViews() {
binding.orderDetailAppBar.topAppBar.title = getString(R.string.order_details_fragment_title)
binding.orderDetailAppBar.topAppBar.setNavigationOnClickListener { findNavController().navigateUp() }
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.orderDetailsConstraintGroup.visibility = View.GONE
if (context != null) {
setProductsAdapter(viewModel.selectedOrder.value?.items)
binding.orderDetailsProRecyclerView.adapter = productsAdapter
}
}
private fun setObservers() {
viewModel.storeDataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.orderDetailsConstraintGroup.visibility = View.GONE
}
else -> {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
}
}
}
viewModel.selectedOrder.observe(viewLifecycleOwner) { orderData ->
if (orderData != null) {
binding.orderDetailsConstraintGroup.visibility = View.VISIBLE
setAllViews(orderData)
val items = orderData.items
val likeList = viewModel.userLikes.value ?: emptyList()
val prosList = viewModel.orderProducts.value ?: emptyList()
productsAdapter.apply {
data = items
proList = prosList
likesList = likeList
}
binding.orderDetailsProRecyclerView.adapter = productsAdapter
binding.orderDetailsProRecyclerView.adapter?.notifyDataSetChanged()
} else {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.orderDetailsConstraintGroup.visibility = View.GONE
}
}
}
private fun setAllViews(orderData: UserData.OrderItem) {
Log.d("OrderDetail", "set all views called")
if (viewModel.isUserASeller) {
binding.orderChangeStatusBtn.visibility = View.VISIBLE
binding.orderChangeStatusBtn.setOnClickListener {
val statusString = orderData.status.split(" ")[0]
val pos = OrderStatus.values().map { it.name }.indexOf(statusString)
showDialogWithItems(pos, orderData.orderId)
}
} else {
binding.orderChangeStatusBtn.visibility = View.GONE
}
val calendar = Calendar.getInstance()
calendar.time = orderData.orderDate
binding.orderDetailsShippingAddLayout.shipDateValueTv.text = getString(
R.string.order_date_text,
Month.values()[(calendar.get(Calendar.MONTH))].name,
calendar.get(Calendar.DAY_OF_MONTH).toString(),
calendar.get(Calendar.YEAR).toString()
)
binding.orderDetailsShippingAddLayout.shipAddValueTv.text =
getCompleteAddress(orderData.deliveryAddress)
binding.orderDetailsShippingAddLayout.shipCurrStatusValueTv.text = orderData.status
setPriceCard(orderData)
}
private fun setPriceCard(orderData: UserData.OrderItem) {
binding.orderDetailsPaymentLayout.priceItemsLabelTv.text = getString(
R.string.price_card_items_string,
getItemsCount(orderData.items).toString()
)
val itemsPriceTotal = getItemsPriceTotal(orderData.itemsPrices, orderData.items)
binding.orderDetailsPaymentLayout.priceItemsAmountTv.text =
getString(
R.string.price_text,
itemsPriceTotal.toString()
)
binding.orderDetailsPaymentLayout.priceShippingAmountTv.text =
getString(R.string.price_text, "0")
binding.orderDetailsPaymentLayout.priceChargesAmountTv.text =
getString(R.string.price_text, "0")
binding.orderDetailsPaymentLayout.priceTotalAmountTv.text =
getString(R.string.price_text, (itemsPriceTotal + orderData.shippingCharges).toString())
}
private fun setProductsAdapter(itemsList: List<UserData.CartItem>?) {
val items = itemsList ?: emptyList()
val likesList = viewModel.userLikes.value ?: emptyList()
val proList = viewModel.orderProducts.value ?: emptyList()
productsAdapter = OrderProductsAdapter(requireContext(), items, proList, likesList)
}
private fun showDialogWithItems(checkedOption: Int = 0, orderId: String) {
val categoryItems: Array<String> = OrderStatus.values().map { it.name }.toTypedArray()
var checkedItem = checkedOption
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.status_dialog_title))
.setSingleChoiceItems(categoryItems, checkedItem) { _, which ->
checkedItem = which
}
.setNegativeButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.pro_cat_dialog_ok_btn)) { dialog, _ ->
if (checkedItem == -1) {
dialog.cancel()
} else {
viewModel.onSetStatusOfOrder(orderId, categoryItems[checkedItem])
}
dialog.cancel()
}
.show()
}
}
private fun getItemsCount(cartItems: List<UserData.CartItem>): Int {
var totalCount = 0
cartItems.forEach {
totalCount += it.quantity
}
return totalCount
}
private fun getItemsPriceTotal(
priceList: Map<String, Double>,
cartItems: List<UserData.CartItem>
): Double {
var totalPrice = 0.0
priceList.forEach { (itemId, price) ->
totalPrice += price * (cartItems.find { it.itemId == itemId }?.quantity ?: 1)
}
return totalPrice
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/AddEditAddressFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.textfield.TextInputLayout
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.AddObjectStatus
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.data.utils.getISOCountriesMap
import com.vishalgaur.shoppingapp.databinding.FragmentAddEditAddressBinding
import com.vishalgaur.shoppingapp.ui.AddAddressViewErrors
import com.vishalgaur.shoppingapp.ui.MyOnFocusChangeListener
import com.vishalgaur.shoppingapp.viewModels.AddEditAddressViewModel
import java.util.*
import kotlin.properties.Delegates
private const val TAG = "AddAddressFragment"
class AddEditAddressFragment : Fragment() {
private lateinit var binding: FragmentAddEditAddressBinding
private val focusChangeListener = MyOnFocusChangeListener()
private val viewModel by viewModels<AddEditAddressViewModel>()
private var isEdit by Delegates.notNull<Boolean>()
private lateinit var addressId: String
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAddEditAddressBinding.inflate(layoutInflater)
isEdit = arguments?.getBoolean("isEdit") == true
addressId = arguments?.getString("addressId").toString()
initViewModel()
setViews()
setObservers()
return binding.root
}
private fun initViewModel() {
viewModel.setIsEdit(isEdit)
if (isEdit) {
viewModel.setAddressData(addressId)
}
}
private fun setViews() {
if (!isEdit) {
binding.addAddressTopAppBar.topAppBar.title = "Add Address"
} else {
binding.addAddressTopAppBar.topAppBar.title = "Edit Address"
}
binding.addAddressTopAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.addressFirstNameEditText.onFocusChangeListener = focusChangeListener
binding.addressLastNameEditText.onFocusChangeListener = focusChangeListener
binding.addressStreetAddEditText.onFocusChangeListener = focusChangeListener
binding.addressStreetAdd2EditText.onFocusChangeListener = focusChangeListener
binding.addressCityEditText.onFocusChangeListener = focusChangeListener
binding.addressStateEditText.onFocusChangeListener = focusChangeListener
binding.addressZipcodeEditText.onFocusChangeListener = focusChangeListener
binding.addressPhoneEditText.onFocusChangeListener = focusChangeListener
setCountrySelectTextField()
binding.addAddressSaveBtn.setOnClickListener {
onAddAddress()
if (viewModel.errorStatus.value?.isEmpty() == true) {
viewModel.addAddressStatus.observe(viewLifecycleOwner) { status ->
if (status == AddObjectStatus.DONE) {
makeToast("Address Saved!")
findNavController().navigateUp()
}
}
}
}
}
private fun setObservers() {
viewModel.errorStatus.observe(viewLifecycleOwner) { errList ->
if (errList.isEmpty()) {
binding.addAddressErrorTextView.visibility = View.GONE
} else {
modifyErrors(errList)
}
}
viewModel.dataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> setLoaderState(View.VISIBLE)
StoreDataStatus.ERROR -> {
setLoaderState()
makeToast("Error getting Data, Try Again!")
}
StoreDataStatus.DONE -> {
fillDataInViews()
setLoaderState()
}
else -> {
setLoaderState()
}
}
}
viewModel.addAddressStatus.observe(viewLifecycleOwner) { status ->
when (status) {
AddObjectStatus.DONE -> setLoaderState()
AddObjectStatus.ERR_ADD -> {
setLoaderState()
binding.addAddressErrorTextView.visibility = View.VISIBLE
binding.addAddressErrorTextView.text =
getString(R.string.save_address_error_text)
makeToast(getString(R.string.save_address_error_text))
}
AddObjectStatus.ADDING -> {
setLoaderState(View.VISIBLE)
}
else -> setLoaderState()
}
}
}
private fun fillDataInViews() {
viewModel.addressData.value?.let { address ->
binding.addAddressTopAppBar.topAppBar.title = "Edit Address"
val countryName = getISOCountriesMap()[address.countryISOCode]
binding.addressCountryEditText.setText(countryName, false)
binding.addressFirstNameEditText.setText(address.fName)
binding.addressLastNameEditText.setText(address.lName)
binding.addressStreetAddEditText.setText(address.streetAddress)
binding.addressStreetAdd2EditText.setText(address.streetAddress2)
binding.addressCityEditText.setText(address.city)
binding.addressStateEditText.setText(address.state)
binding.addressZipcodeEditText.setText(address.zipCode)
binding.addressPhoneEditText.setText(address.phoneNumber.substringAfter("+91"))
binding.addAddressSaveBtn.setText(R.string.save_address_btn_text)
}
}
private fun makeToast(errText: String) {
Toast.makeText(context, errText, Toast.LENGTH_LONG).show()
}
private fun setLoaderState(isVisible: Int = View.GONE) {
binding.loaderLayout.loaderFrameLayout.visibility = isVisible
if (isVisible == View.GONE) {
binding.loaderLayout.circularLoader.hideAnimationBehavior
} else {
binding.loaderLayout.circularLoader.showAnimationBehavior
}
}
private fun onAddAddress() {
val countryName = binding.addressCountryEditText.text.toString()
val firstName = binding.addressFirstNameEditText.text.toString()
val lastName = binding.addressLastNameEditText.text.toString()
val streetAdd = binding.addressStreetAddEditText.text.toString()
val streetAdd2 = binding.addressStreetAdd2EditText.text.toString()
val city = binding.addressCityEditText.text.toString()
val state = binding.addressStateEditText.text.toString()
val zipCode = binding.addressZipcodeEditText.text.toString()
val phoneNumber = binding.addressPhoneEditText.text.toString()
val countryCode =
getISOCountriesMap().keys.find { Locale("", it).displayCountry == countryName }
Log.d(TAG, "onAddAddress: Add/Edit Address Initiated")
viewModel.submitAddress(
countryCode!!,
firstName,
lastName,
streetAdd,
streetAdd2,
city,
state,
zipCode,
phoneNumber
)
}
private fun setCountrySelectTextField() {
val isoCountriesMap = getISOCountriesMap()
val countries = isoCountriesMap.values.toSortedSet().toList()
val defaultCountry = Locale.getDefault().displayCountry
val countryAdapter = ArrayAdapter(requireContext(), R.layout.country_list_item, countries)
(binding.addressCountryEditText as? AutoCompleteTextView)?.let {
it.setText(defaultCountry, false)
it.setAdapter(countryAdapter)
}
}
private fun modifyErrors(errList: List<AddAddressViewErrors>) {
binding.fNameOutlinedTextField.error = null
binding.lNameOutlinedTextField.error = null
binding.streetAddOutlinedTextField.error = null
binding.cityOutlinedTextField.error = null
binding.stateOutlinedTextField.error = null
binding.zipCodeOutlinedTextField.error = null
binding.phoneOutlinedTextField.error = null
errList.forEach { err ->
when (err) {
AddAddressViewErrors.EMPTY -> setEditTextsError(true)
AddAddressViewErrors.ERR_FNAME_EMPTY ->
setEditTextsError(true, binding.fNameOutlinedTextField)
AddAddressViewErrors.ERR_LNAME_EMPTY ->
setEditTextsError(true, binding.lNameOutlinedTextField)
AddAddressViewErrors.ERR_STR1_EMPTY ->
setEditTextsError(true, binding.streetAddOutlinedTextField)
AddAddressViewErrors.ERR_CITY_EMPTY ->
setEditTextsError(true, binding.cityOutlinedTextField)
AddAddressViewErrors.ERR_STATE_EMPTY ->
setEditTextsError(true, binding.stateOutlinedTextField)
AddAddressViewErrors.ERR_ZIP_EMPTY ->
setEditTextsError(true, binding.zipCodeOutlinedTextField)
AddAddressViewErrors.ERR_ZIP_INVALID ->
setEditTextsError(false, binding.zipCodeOutlinedTextField)
AddAddressViewErrors.ERR_PHONE_INVALID ->
setEditTextsError(false, binding.phoneOutlinedTextField)
AddAddressViewErrors.ERR_PHONE_EMPTY ->
setEditTextsError(true, binding.phoneOutlinedTextField)
}
}
}
private fun setEditTextsError(isEmpty: Boolean, editText: TextInputLayout? = null) {
if (isEmpty) {
binding.addAddressErrorTextView.visibility = View.VISIBLE
if (editText != null) {
editText.error = "Please Fill the Form"
editText.errorIconDrawable = null
}
} else {
binding.addAddressErrorTextView.visibility = View.GONE
editText!!.error = "Invalid!"
editText.errorIconDrawable = null
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/OrdersAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.databinding.LayoutOrderSummaryCardBinding
import java.time.Month
import java.util.*
class OrdersAdapter(ordersList: List<UserData.OrderItem>, private val context: Context) :
RecyclerView.Adapter<OrdersAdapter.ViewHolder>() {
lateinit var onClickListener: OnClickListener
var data: List<UserData.OrderItem> = ordersList
inner class ViewHolder(private val binding: LayoutOrderSummaryCardBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(orderData: UserData.OrderItem) {
binding.orderSummaryCard.setOnClickListener { onClickListener.onCardClick(orderData.orderId) }
binding.orderSummaryIdTv.text = orderData.orderId
val calendar = Calendar.getInstance()
calendar.time = orderData.orderDate
binding.orderSummaryDateTv.text =
context.getString(
R.string.order_date_text,
Month.values()[(calendar.get(Calendar.MONTH))].name,
calendar.get(Calendar.DAY_OF_MONTH).toString(),
calendar.get(Calendar.YEAR).toString()
)
binding.orderSummaryStatusValueTv.text = orderData.status
val totalItems = orderData.items.map { it.quantity }.sum()
binding.orderSummaryItemsCountTv.text =
context.getString(R.string.order_items_count_text, totalItems.toString())
var totalAmount = 0.0
orderData.itemsPrices.forEach { (itemId, price) ->
totalAmount += price * (orderData.items.find { it.itemId == itemId }?.quantity ?: 1)
}
binding.orderSummaryTotalAmountTv.text =
context.getString(R.string.price_text, totalAmount.toString())
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutOrderSummaryCardBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun getItemCount() = data.size
interface OnClickListener {
fun onCardClick(orderId: String)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/loginSignup/LoginSignupBaseFragment.kt
package com.vishalgaur.shoppingapp.ui.loginSignup
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.viewbinding.ViewBinding
import com.vishalgaur.shoppingapp.ui.MyOnFocusChangeListener
import com.vishalgaur.shoppingapp.viewModels.AuthViewModel
abstract class LoginSignupBaseFragment<VBinding : ViewBinding> : Fragment() {
protected val viewModel: AuthViewModel by activityViewModels()
protected lateinit var binding: VBinding
protected abstract fun setViewBinding(): VBinding
protected val focusChangeListener = MyOnFocusChangeListener()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
init()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setUpViews()
observeView()
return binding.root
}
fun launchOtpActivity(from: String, extras: Bundle) {
val intent = Intent(context, OtpActivity::class.java).putExtra(
"from",
from
).putExtras(extras)
startActivity(intent)
}
open fun setUpViews() {}
open fun observeView() {}
private fun init() {
binding = setViewBinding()
}
interface OnClickListener : View.OnClickListener
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/repository/AuthRepository.kt
package com.vishalgaur.shoppingapp.data.source.repository
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException
import com.google.firebase.auth.PhoneAuthCredential
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.source.UserDataSource
import com.vishalgaur.shoppingapp.data.utils.SignUpErrors
import com.vishalgaur.shoppingapp.data.utils.UserType
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.supervisorScope
class AuthRepository(
private val userLocalDataSource: UserDataSource,
private val authRemoteDataSource: UserDataSource,
private var sessionManager: ShoppingAppSessionManager
) : AuthRepoInterface {
private var firebaseAuth: FirebaseAuth = Firebase.auth
companion object {
private const val TAG = "AuthRepository"
}
override fun getFirebaseAuth() = firebaseAuth
override fun isRememberMeOn() = sessionManager.isRememberMeOn()
override suspend fun refreshData() {
Log.d(TAG, "refreshing userdata")
if (sessionManager.isLoggedIn()) {
updateUserInLocalSource(sessionManager.getPhoneNumber())
} else {
sessionManager.logoutFromSession()
deleteUserFromLocalSource()
}
}
override suspend fun signUp(userData: UserData) {
val isSeller = userData.userType == UserType.SELLER.name
sessionManager.createLoginSession(
userData.userId,
userData.name,
userData.mobile,
false,
isSeller
)
Log.d(TAG, "on SignUp: Updating user in Local Source")
userLocalDataSource.addUser(userData)
Log.d(TAG, "on SignUp: Updating userdata on Remote Source")
authRemoteDataSource.addUser(userData)
authRemoteDataSource.updateEmailsAndMobiles(userData.email, userData.mobile)
}
override fun login(userData: UserData, rememberMe: Boolean) {
val isSeller = userData.userType == UserType.SELLER.name
sessionManager.createLoginSession(
userData.userId,
userData.name,
userData.mobile,
rememberMe,
isSeller
)
}
override suspend fun checkEmailAndMobile(
email: String,
mobile: String,
context: Context
): SignUpErrors? {
Log.d(TAG, "on SignUp: Checking email and mobile")
var sErr: SignUpErrors? = null
val queryResult = authRemoteDataSource.getEmailsAndMobiles()
if (queryResult != null) {
val mob = queryResult.mobiles.contains(mobile)
val em = queryResult.emails.contains(email)
if (!mob && !em) {
sErr = SignUpErrors.NONE
} else {
sErr = SignUpErrors.SERR
when {
!mob && em -> makeErrToast("Email is already registered!", context)
mob && !em -> makeErrToast("Mobile is already registered!", context)
mob && em -> makeErrToast("Email and mobile is already registered!", context)
}
}
}
return sErr
}
override suspend fun checkLogin(mobile: String, password: String): UserData? {
Log.d(TAG, "on Login: checking mobile and password")
val queryResult =
authRemoteDataSource.getUserByMobileAndPassword(mobile, password)
return if (queryResult.size > 0) {
queryResult[0]
} else {
null
}
}
override fun signInWithPhoneAuthCredential(
credential: PhoneAuthCredential,
isUserLoggedIn: MutableLiveData<Boolean>, context: Context
) {
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "signInWithCredential:success")
val user = task.result?.user
if (user != null) {
isUserLoggedIn.postValue(true)
}
} else {
Log.w(TAG, "signInWithCredential:failure", task.exception)
if (task.exception is FirebaseAuthInvalidCredentialsException) {
Log.d(TAG, "createUserWithMobile:failure", task.exception)
isUserLoggedIn.postValue(false)
makeErrToast("Wrong OTP!", context)
}
}
}
}
override suspend fun signOut() {
sessionManager.logoutFromSession()
firebaseAuth.signOut()
userLocalDataSource.clearUser()
}
private fun makeErrToast(text: String, context: Context) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show()
}
private suspend fun deleteUserFromLocalSource() {
userLocalDataSource.clearUser()
}
private suspend fun updateUserInLocalSource(phoneNumber: String?) {
coroutineScope {
launch {
if (phoneNumber != null) {
val getUser = userLocalDataSource.getUserByMobile(phoneNumber)
if (getUser == null) {
userLocalDataSource.clearUser()
val uData = authRemoteDataSource.getUserByMobile(phoneNumber)
if (uData != null) {
userLocalDataSource.addUser(uData)
}
}
}
}
}
}
override suspend fun hardRefreshUserData() {
userLocalDataSource.clearUser()
val mobile = sessionManager.getPhoneNumber()
if (mobile != null) {
val uData = authRemoteDataSource.getUserByMobile(mobile)
if (uData != null) {
userLocalDataSource.addUser(uData)
}
}
}
override suspend fun insertProductToLikes(productId: String, userId: String): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onLikeProduct: adding product to remote source")
authRemoteDataSource.likeProduct(productId, userId)
}
val localRes = async {
Log.d(TAG, "onLikeProduct: updating product to local source")
userLocalDataSource.likeProduct(productId, userId)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun removeProductFromLikes(
productId: String,
userId: String
): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onDislikeProduct: deleting product from remote source")
authRemoteDataSource.dislikeProduct(productId, userId)
}
val localRes = async {
Log.d(TAG, "onDislikeProduct: updating product to local source")
userLocalDataSource.dislikeProduct(productId, userId)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun insertAddress(
newAddress: UserData.Address,
userId: String
): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onInsertAddress: adding address to remote source")
authRemoteDataSource.insertAddress(newAddress, userId)
}
val localRes = async {
Log.d(TAG, "onInsertAddress: updating address to local source")
val userRes = authRemoteDataSource.getUserById(userId)
if (userRes is Success) {
userLocalDataSource.clearUser()
userLocalDataSource.addUser(userRes.data!!)
} else if (userRes is Error) {
throw userRes.exception
}
}
try {
remoteRes.await()
localRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun updateAddress(
newAddress: UserData.Address,
userId: String
): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onUpdateAddress: updating address on remote source")
authRemoteDataSource.updateAddress(newAddress, userId)
}
val localRes = async {
Log.d(TAG, "onUpdateAddress: updating address on local source")
val userRes =
authRemoteDataSource.getUserById(userId)
if (userRes is Success) {
userLocalDataSource.clearUser()
userLocalDataSource.addUser(userRes.data!!)
} else if (userRes is Error) {
throw userRes.exception
}
}
try {
remoteRes.await()
localRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun deleteAddressById(addressId: String, userId: String): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onDelete: deleting address from remote source")
authRemoteDataSource.deleteAddress(addressId, userId)
}
val localRes = async {
Log.d(TAG, "onDelete: deleting address from local source")
val userRes =
authRemoteDataSource.getUserById(userId)
if (userRes is Success) {
userLocalDataSource.clearUser()
userLocalDataSource.addUser(userRes.data!!)
} else if (userRes is Error) {
throw userRes.exception
}
}
try {
remoteRes.await()
localRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun insertCartItemByUserId(
cartItem: UserData.CartItem,
userId: String
): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onInsertCartItem: adding item to remote source")
authRemoteDataSource.insertCartItem(cartItem, userId)
}
val localRes = async {
Log.d(TAG, "onInsertCartItem: updating item to local source")
userLocalDataSource.insertCartItem(cartItem, userId)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun updateCartItemByUserId(
cartItem: UserData.CartItem,
userId: String
): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onUpdateCartItem: updating cart item on remote source")
authRemoteDataSource.updateCartItem(cartItem, userId)
}
val localRes = async {
Log.d(TAG, "onUpdateCartItem: updating cart item on local source")
userLocalDataSource.updateCartItem(cartItem, userId)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun deleteCartItemByUserId(itemId: String, userId: String): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onDelete: deleting cart item from remote source")
authRemoteDataSource.deleteCartItem(itemId, userId)
}
val localRes = async {
Log.d(TAG, "onDelete: deleting cart item from local source")
userLocalDataSource.deleteCartItem(itemId, userId)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun placeOrder(newOrder: UserData.OrderItem, userId: String): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onPlaceOrder: adding item to remote source")
authRemoteDataSource.placeOrder(newOrder, userId)
}
val localRes = async {
Log.d(TAG, "onPlaceOrder: adding item to local source")
val userRes = authRemoteDataSource.getUserById(userId)
if (userRes is Success) {
userLocalDataSource.clearUser()
userLocalDataSource.addUser(userRes.data!!)
} else if (userRes is Error) {
throw userRes.exception
}
}
try {
remoteRes.await()
localRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun setStatusOfOrder(
orderId: String,
userId: String,
status: String
): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onSetStatus: updating status on remote source")
authRemoteDataSource.setStatusOfOrderByUserId(orderId, userId, status)
}
val localRes = async {
Log.d(TAG, "onSetStatus: updating status on local source")
userLocalDataSource.setStatusOfOrderByUserId(orderId, userId, status)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun getOrdersByUserId(userId: String): Result<List<UserData.OrderItem>?> {
return userLocalDataSource.getOrdersByUserId(userId)
}
override suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?> {
return userLocalDataSource.getAddressesByUserId(userId)
}
override suspend fun getLikesByUserId(userId: String): Result<List<String>?> {
return userLocalDataSource.getLikesByUserId(userId)
}
override suspend fun getUserData(userId: String): Result<UserData?> {
return userLocalDataSource.getUserById(userId)
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/FakeUserDataSource.kt
package com.vishalgaur.shoppingapp.data.source
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.EmailMobileData
class FakeUserDataSource(private var uData: UserData?) : UserDataSource {
private var emailMobileData = EmailMobileData()
override suspend fun addUser(userData: UserData) {
uData = userData
}
override suspend fun getUserById(userId: String): Result<UserData?> {
uData?.let {
if (it.userId == userId) {
return Success(it)
}
}
return Error(Exception("User Not Found"))
}
override suspend fun getEmailsAndMobiles(): EmailMobileData {
return emailMobileData
}
override suspend fun getUserByMobileAndPassword(
mobile: String,
password: String
): MutableList<UserData> {
val res = mutableListOf<UserData>()
uData?.let {
if (it.mobile == mobile && it.password == <PASSWORD>) {
res.add(it)
}
}
return res
}
override suspend fun clearUser() {
uData = null
}
override suspend fun getUserByMobile(phoneNumber: String): UserData? {
return super.getUserByMobile(phoneNumber)
}
override fun updateEmailsAndMobiles(email: String, mobile: String) {
emailMobileData.emails.add(email)
emailMobileData.mobiles.add(mobile)
}
override suspend fun likeProduct(productId: String, userId: String) {
uData?.let {
if (it.userId == userId) {
val likes = it.likes.toMutableList()
likes.add(productId)
it.likes = likes
}
}
}
override suspend fun dislikeProduct(productId: String, userId: String) {
uData?.let {
if (it.userId == userId) {
val likes = it.likes.toMutableList()
likes.remove(productId)
it.likes = likes
}
}
}
override suspend fun insertAddress(newAddress: UserData.Address, userId: String) {
uData?.let {
if (it.userId == userId) {
val addresses = it.addresses.toMutableList()
addresses.add(newAddress)
it.addresses = addresses
}
}
}
override suspend fun updateAddress(newAddress: UserData.Address, userId: String) {
uData?.let { data ->
if (data.userId == userId) {
val addresses = data.addresses.toMutableList()
val pos = data.addresses.indexOfFirst { it.addressId == newAddress.addressId }
if (pos >= 0) {
addresses[pos] = newAddress
}
data.addresses = addresses
}
}
}
override suspend fun deleteAddress(addressId: String, userId: String) {
uData?.let { data ->
if (data.userId == userId) {
val addresses = data.addresses.toMutableList()
val pos = data.addresses.indexOfFirst { it.addressId == addressId }
if (pos >= 0) {
addresses.removeAt(pos)
}
data.addresses = addresses
}
}
}
override suspend fun insertCartItem(newItem: UserData.CartItem, userId: String) {
uData?.let {
if (it.userId == userId) {
val cart = it.cart.toMutableList()
cart.add(newItem)
it.cart = cart
}
}
}
override suspend fun updateCartItem(item: UserData.CartItem, userId: String) {
uData?.let { data ->
if (data.userId == userId) {
val cart = data.cart.toMutableList()
val pos = data.cart.indexOfFirst { it.itemId == item.itemId }
if (pos >= 0) {
cart[pos] = item
}
data.cart = cart
}
}
}
override suspend fun deleteCartItem(itemId: String, userId: String) {
uData?.let { data ->
if (data.userId == userId) {
val cart = data.cart.toMutableList()
val pos = data.cart.indexOfFirst { it.itemId == itemId }
if (pos >= 0) {
cart.removeAt(pos)
}
data.cart = cart
}
}
}
override suspend fun getAddressesByUserId(userId: String): Result<List<UserData.Address>?> {
uData?.let {
if (it.userId == userId) {
return Success(it.addresses)
}
}
return Error(Exception("User Not Found"))
}
override suspend fun getLikesByUserId(userId: String): Result<List<String>?> {
uData?.let {
if (it.userId == userId) {
return Success(it.likes)
}
}
return Error(Exception("User Not Found"))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/AddProductImagesAdapter.kt
package com.vishalgaur.shoppingapp.ui.home
import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.vishalgaur.shoppingapp.databinding.AddImagesItemBinding
class AddProductImagesAdapter(private val context: Context, images: List<Uri>) :
RecyclerView.Adapter<AddProductImagesAdapter.ViewHolder>() {
private var data: MutableList<Uri> = images as MutableList<Uri>
inner class ViewHolder(private var binding: AddImagesItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(imgUrl: Uri, pos: Int) {
binding.addImgCloseBtn.setOnClickListener {
deleteItem(pos)
}
if (imgUrl.toString().contains("https://")) {
Glide.with(context)
.asBitmap()
.load(imgUrl.buildUpon().scheme("https").build())
.into(binding.addImagesImageView)
} else {
binding.addImagesImageView.setImageURI(imgUrl)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
AddImagesItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val imageUrl = data[position]
holder.bind(imageUrl, position)
}
override fun getItemCount(): Int = data.size
fun deleteItem(index: Int) {
data.removeAt(index)
notifyDataSetChanged()
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/repository/ProductsRepository.kt
package com.vishalgaur.shoppingapp.data.source.repository
import android.net.Uri
import android.util.Log
import androidx.core.net.toUri
import androidx.lifecycle.LiveData
import com.vishalgaur.shoppingapp.ERR_UPLOAD
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.*
import com.vishalgaur.shoppingapp.data.source.ProductDataSource
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import kotlinx.coroutines.async
import kotlinx.coroutines.supervisorScope
import java.util.*
class ProductsRepository(
private val productsRemoteSource: ProductDataSource,
private val productsLocalSource: ProductDataSource
) : ProductsRepoInterface {
companion object {
private const val TAG = "ProductsRepository"
}
override suspend fun refreshProducts(): StoreDataStatus? {
Log.d(TAG, "Updating Products in Room")
return updateProductsFromRemoteSource()
}
override fun observeProducts(): LiveData<Result<List<Product>>?> {
return productsLocalSource.observeProducts()
}
override fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?> {
return productsLocalSource.observeProductsByOwner(ownerId)
}
override suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>> {
return productsLocalSource.getAllProductsByOwner(ownerId)
}
override suspend fun getProductById(productId: String, forceUpdate: Boolean): Result<Product> {
if (forceUpdate) {
updateProductFromRemoteSource(productId)
}
return productsLocalSource.getProductById(productId)
}
override suspend fun insertProduct(newProduct: Product): Result<Boolean> {
return supervisorScope {
val localRes = async {
Log.d(TAG, "onInsertProduct: adding product to local source")
productsLocalSource.insertProduct(newProduct)
}
val remoteRes = async {
Log.d(TAG, "onInsertProduct: adding product to remote source")
productsRemoteSource.insertProduct(newProduct)
}
try {
localRes.await()
remoteRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun insertImages(imgList: List<Uri>): List<String> {
var urlList = mutableListOf<String>()
imgList.forEach label@{ uri ->
val uniId = UUID.randomUUID().toString()
val fileName = uniId + uri.lastPathSegment?.split("/")?.last()
try {
val downloadUrl = productsRemoteSource.uploadImage(uri, fileName)
urlList.add(downloadUrl.toString())
} catch (e: Exception) {
productsRemoteSource.revertUpload(fileName)
Log.d(TAG, "exception: message = $e")
urlList = mutableListOf()
urlList.add(ERR_UPLOAD)
return@label
}
}
return urlList
}
override suspend fun updateProduct(product: Product): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onUpdate: updating product in remote source")
productsRemoteSource.updateProduct(product)
}
val localRes = async {
Log.d(TAG, "onUpdate: updating product in local source")
productsLocalSource.insertProduct(product)
}
try {
remoteRes.await()
localRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
override suspend fun updateImages(newList: List<Uri>, oldList: List<String>): List<String> {
var urlList = mutableListOf<String>()
newList.forEach label@{ uri ->
if (!oldList.contains(uri.toString())) {
val uniId = UUID.randomUUID().toString()
val fileName = uniId + uri.lastPathSegment?.split("/")?.last()
try {
val downloadUrl = productsRemoteSource.uploadImage(uri, fileName)
urlList.add(downloadUrl.toString())
} catch (e: Exception) {
productsRemoteSource.revertUpload(fileName)
Log.d(TAG, "exception: message = $e")
urlList = mutableListOf()
urlList.add(ERR_UPLOAD)
return@label
}
} else {
urlList.add(uri.toString())
}
}
oldList.forEach { imgUrl ->
if (!newList.contains(imgUrl.toUri())) {
productsRemoteSource.deleteImage(imgUrl)
}
}
return urlList
}
override suspend fun deleteProductById(productId: String): Result<Boolean> {
return supervisorScope {
val remoteRes = async {
Log.d(TAG, "onDelete: deleting product from remote source")
productsRemoteSource.deleteProduct(productId)
}
val localRes = async {
Log.d(TAG, "onDelete: deleting product from local source")
productsLocalSource.deleteProduct(productId)
}
try {
remoteRes.await()
localRes.await()
Success(true)
} catch (e: Exception) {
Error(e)
}
}
}
private suspend fun updateProductsFromRemoteSource(): StoreDataStatus? {
var res: StoreDataStatus? = null
try {
val remoteProducts = productsRemoteSource.getAllProducts()
if (remoteProducts is Success) {
Log.d(TAG, "pro list = ${remoteProducts.data}")
productsLocalSource.deleteAllProducts()
productsLocalSource.insertMultipleProducts(remoteProducts.data)
res = StoreDataStatus.DONE
} else {
res = StoreDataStatus.ERROR
if (remoteProducts is Error)
throw remoteProducts.exception
}
} catch (e: Exception) {
Log.d(TAG, "onUpdateProductsFromRemoteSource: Exception occurred, ${e.message}")
}
return res
}
private suspend fun updateProductFromRemoteSource(productId: String): StoreDataStatus? {
var res: StoreDataStatus? = null
try {
val remoteProduct = productsRemoteSource.getProductById(productId)
if (remoteProduct is Success) {
productsLocalSource.insertProduct(remoteProduct.data)
res = StoreDataStatus.DONE
} else {
res = StoreDataStatus.ERROR
if (remoteProduct is Error)
throw remoteProduct.exception
}
} catch (e: Exception) {
Log.d(TAG, "onUpdateProductFromRemoteSource: Exception occurred, ${e.message}")
}
return res
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/ProductViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.AddObjectStatus
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.ui.AddItemErrors
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.*
private const val TAG = "ProductViewModel"
class ProductViewModel(private val productId: String, application: Application) :
AndroidViewModel(application) {
private val _productData = MutableLiveData<Product?>()
val productData: LiveData<Product?> get() = _productData
private val _dataStatus = MutableLiveData<StoreDataStatus>()
val dataStatus: LiveData<StoreDataStatus> get() = _dataStatus
private val _errorStatus = MutableLiveData<List<AddItemErrors>>()
val errorStatus: LiveData<List<AddItemErrors>> get() = _errorStatus
private val _addItemStatus = MutableLiveData<AddObjectStatus?>()
val addItemStatus: LiveData<AddObjectStatus?> get() = _addItemStatus
private val _isLiked = MutableLiveData<Boolean>()
val isLiked: LiveData<Boolean> get() = _isLiked
private val _isItemInCart = MutableLiveData<Boolean>()
val isItemInCart: LiveData<Boolean> get() = _isItemInCart
private val productsRepository =(application as ShoppingApplication).productsRepository
private val authRepository = (application as ShoppingApplication).authRepository
private val sessionManager = ShoppingAppSessionManager(application.applicationContext)
private val currentUserId = sessionManager.getUserIdFromSession()
init {
_isLiked.value = false
_errorStatus.value = emptyList()
viewModelScope.launch {
Log.d(TAG, "init: productId: $productId")
getProductDetails()
checkIfInCart()
setLike()
}
}
private fun getProductDetails() {
viewModelScope.launch {
_dataStatus.value = StoreDataStatus.LOADING
try {
Log.d(TAG, "getting product Data")
val res = productsRepository.getProductById(productId)
if (res is Success) {
_productData.value = res.data
_dataStatus.value = StoreDataStatus.DONE
} else if (res is Error) {
throw Exception("Error getting product")
}
} catch (e: Exception) {
_productData.value = Product()
_dataStatus.value = StoreDataStatus.ERROR
}
}
}
fun setLike() {
viewModelScope.launch {
val res = authRepository.getLikesByUserId(currentUserId!!)
if (res is Success) {
val userLikes = res.data ?: emptyList()
_isLiked.value = userLikes.contains(productId)
Log.d(TAG, "Setting Like: Success, value = ${_isLiked.value}, ${res.data?.size}")
} else {
if (res is Error)
Log.d(TAG, "Getting Likes: Error Occurred, ${res.exception.message}")
}
}
}
fun toggleLikeProduct() {
Log.d(TAG, "toggling Like")
viewModelScope.launch {
val deferredRes = async {
if (_isLiked.value == true) {
authRepository.removeProductFromLikes(productId, currentUserId!!)
} else {
authRepository.insertProductToLikes(productId, currentUserId!!)
}
}
val res = deferredRes.await()
if (res is Success) {
_isLiked.value = !_isLiked.value!!
} else{
if(res is Error)
Log.d(TAG, "Error toggling like, ${res.exception}")
}
}
}
fun isSeller() = sessionManager.isUserSeller()
fun checkIfInCart() {
viewModelScope.launch {
val deferredRes = async { authRepository.getUserData(currentUserId!!) }
val userRes = deferredRes.await()
if (userRes is Success) {
val uData = userRes.data
if (uData != null) {
val cartList = uData.cart
val idx = cartList.indexOfFirst { it.productId == productId }
_isItemInCart.value = idx >= 0
Log.d(TAG, "Checking in Cart: Success, value = ${_isItemInCart.value}, ${cartList.size}")
} else {
_isItemInCart.value = false
}
} else {
_isItemInCart.value = false
}
}
}
fun addToCart(size: Int?, color: String?) {
val errList = mutableListOf<AddItemErrors>()
if (size == null) errList.add(AddItemErrors.ERROR_SIZE)
if (color.isNullOrBlank()) errList.add(AddItemErrors.ERROR_COLOR)
if (errList.isEmpty()) {
val itemId = UUID.randomUUID().toString()
val newItem = UserData.CartItem(
itemId, productId, productData.value!!.owner, 1, color, size
)
insertCartItem(newItem)
}
}
private fun insertCartItem(item: UserData.CartItem) {
viewModelScope.launch {
_addItemStatus.value = AddObjectStatus.ADDING
val deferredRes = async {
authRepository.insertCartItemByUserId(item, currentUserId!!)
}
val res = deferredRes.await()
if (res is Success) {
Log.d(TAG, "onAddItem: Success")
_addItemStatus.value = AddObjectStatus.DONE
} else {
_addItemStatus.value = AddObjectStatus.ERR_ADD
if (res is Error) {
Log.d(TAG, "onAddItem: Error, ${res.exception.message}")
}
}
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/HomeFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.CheckBox
import android.widget.ImageView
import androidx.core.os.bundleOf
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.utils.ProductCategories
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentHomeBinding
import com.vishalgaur.shoppingapp.ui.MyOnFocusChangeListener
import com.vishalgaur.shoppingapp.ui.RecyclerViewPaddingItemDecoration
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
import kotlinx.coroutines.*
private const val TAG = "HomeFragment"
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private val viewModel: HomeViewModel by activityViewModels()
private val focusChangeListener = MyOnFocusChangeListener()
private lateinit var productAdapter: ProductAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentHomeBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getUserLikes()
}
// override fun onResume() {
// super.onResume()
// viewModel.getLikedProducts()
// }
private fun setViews() {
setHomeTopAppBar()
if (context != null) {
setProductsAdapter(viewModel.products.value)
binding.productsRecyclerView.apply {
val gridLayoutManager = GridLayoutManager(context, 2)
gridLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return when (productAdapter.getItemViewType(position)) {
2 -> 2 //ad
else -> {
val proCount = productAdapter.data.count { it is Product }
val adCount = productAdapter.data.size - proCount
val totalCount = proCount + (adCount * 2)
// product, full for last item
if (position + 1 == productAdapter.data.size && totalCount % 2 == 1) 2 else 1
}
}
}
}
layoutManager = gridLayoutManager
adapter = productAdapter
val itemDecoration = RecyclerViewPaddingItemDecoration(requireContext())
if (itemDecorationCount == 0) {
addItemDecoration(itemDecoration)
}
}
}
if (!viewModel.isUserASeller) {
binding.homeFabAddProduct.visibility = View.GONE
}
binding.homeFabAddProduct.setOnClickListener {
showDialogWithItems(ProductCategories, 0, false)
}
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
private fun setObservers() {
viewModel.storeDataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.productsRecyclerView.visibility = View.GONE
}
else -> {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
}
}
if (status != null && status != StoreDataStatus.LOADING) {
viewModel.products.observe(viewLifecycleOwner) { productsList ->
if (productsList.isNotEmpty()) {
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.productsRecyclerView.visibility = View.VISIBLE
binding.productsRecyclerView.adapter?.apply {
productAdapter.data =
getMixedDataList(productsList, getAdsList())
notifyDataSetChanged()
}
}
}
}
}
viewModel.allProducts.observe(viewLifecycleOwner) {
if (it.isNotEmpty()) {
viewModel.setDataLoaded()
viewModel.filterProducts("All")
}
}
viewModel.userLikes.observe(viewLifecycleOwner) {
if (it.isNotEmpty()) {
binding.productsRecyclerView.adapter?.apply {
notifyDataSetChanged()
}
}
}
}
private fun performSearch(query: String) {
viewModel.filterBySearch(query)
}
private fun setAppBarItemClicks(menuItem: MenuItem): Boolean {
return when (menuItem.itemId) {
R.id.home_filter -> {
val extraFilters = arrayOf("All", "None")
val categoryList = ProductCategories.plus(extraFilters)
val checkedItem = categoryList.indexOf(viewModel.filterCategory.value)
showDialogWithItems(categoryList, checkedItem, true)
true
}
R.id.home_favorites -> {
// show favorite products list
findNavController().navigate(R.id.action_homeFragment_to_favoritesFragment)
true
}
else -> false
}
}
private fun setHomeTopAppBar() {
var lastInput = ""
val debounceJob: Job? = null
val uiScope = CoroutineScope(Dispatchers.Main + SupervisorJob())
binding.homeTopAppBar.topAppBar.inflateMenu(R.menu.home_app_bar_menu)
if (viewModel.isUserASeller) {
binding.homeTopAppBar.topAppBar.menu.removeItem(R.id.home_favorites)
}
binding.homeTopAppBar.homeSearchEditText.onFocusChangeListener = focusChangeListener
binding.homeTopAppBar.homeSearchEditText.doAfterTextChanged { editable ->
if (editable != null) {
val newtInput = editable.toString()
debounceJob?.cancel()
if (lastInput != newtInput) {
lastInput = newtInput
uiScope.launch {
delay(500)
if (lastInput == newtInput) {
performSearch(newtInput)
}
}
}
}
}
binding.homeTopAppBar.homeSearchEditText.setOnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
textView.clearFocus()
val inputManager =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(textView.windowToken, 0)
performSearch(textView.text.toString())
true
} else {
false
}
}
binding.homeTopAppBar.searchOutlinedTextLayout.setEndIconOnClickListener {
it.clearFocus()
binding.homeTopAppBar.homeSearchEditText.setText("")
val inputManager =
requireContext().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(it.windowToken, 0)
// viewModel.filterProducts("All")
}
binding.homeTopAppBar.topAppBar.setOnMenuItemClickListener { menuItem ->
setAppBarItemClicks(menuItem)
}
}
private fun setProductsAdapter(productsList: List<Product>?) {
val likesList = viewModel.userLikes.value ?: emptyList()
productAdapter = ProductAdapter(productsList ?: emptyList(), likesList, requireContext())
productAdapter.onClickListener = object : ProductAdapter.OnClickListener {
override fun onClick(productData: Product) {
findNavController().navigate(
R.id.action_seeProduct,
bundleOf("productId" to productData.productId)
)
}
override fun onDeleteClick(productData: Product) {
Log.d(TAG, "onDeleteProduct: initiated for ${productData.productId}")
showDeleteDialog(productData.name, productData.productId)
}
override fun onEditClick(productId: String) {
Log.d(TAG, "onEditProduct: initiated for $productId")
navigateToAddEditProductFragment(isEdit = true, productId = productId)
}
override fun onLikeClick(productId: String) {
Log.d(TAG, "onToggleLike: initiated for $productId")
viewModel.toggleLikeByProductId(productId)
}
override fun onAddToCartClick(productData: Product) {
Log.d(TAG, "onToggleCartAddition: initiated")
viewModel.toggleProductInCart(productData)
}
}
productAdapter.bindImageButtons = object : ProductAdapter.BindImageButtons {
@SuppressLint("ResourceAsColor")
override fun setLikeButton(productId: String, button: CheckBox) {
button.isChecked = viewModel.isProductLiked(productId)
}
override fun setCartButton(productId: String, imgView: ImageView) {
if (viewModel.isProductInCart(productId)) {
imgView.setImageResource(R.drawable.ic_remove_shopping_cart_24)
} else {
imgView.setImageResource(R.drawable.ic_add_shopping_cart_24)
}
}
}
}
private fun showDeleteDialog(productName: String, productId: String) {
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.delete_dialog_title_text))
.setMessage(getString(R.string.delete_dialog_message_text, productName))
.setNegativeButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.delete_dialog_delete_btn_text)) { dialog, _ ->
viewModel.deleteProduct(productId)
dialog.cancel()
}
.show()
}
}
private fun showDialogWithItems(
categoryItems: Array<String>,
checkedOption: Int = 0,
isFilter: Boolean
) {
var checkedItem = checkedOption
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.pro_cat_dialog_title))
.setSingleChoiceItems(categoryItems, checkedItem) { _, which ->
checkedItem = which
}
.setNegativeButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.pro_cat_dialog_ok_btn)) { dialog, _ ->
if (checkedItem == -1) {
dialog.cancel()
} else {
if (isFilter) {
viewModel.filterProducts(categoryItems[checkedItem])
} else {
navigateToAddEditProductFragment(
isEdit = false,
catName = categoryItems[checkedItem]
)
}
}
dialog.cancel()
}
.show()
}
}
private fun navigateToAddEditProductFragment(
isEdit: Boolean,
catName: String? = null,
productId: String? = null
) {
findNavController().navigate(
R.id.action_goto_addProduct,
bundleOf("isEdit" to isEdit, "categoryName" to catName, "productId" to productId)
)
}
private fun getMixedDataList(data: List<Product>, adsList: List<Int>): List<Any> {
val itemsList = mutableListOf<Any>()
itemsList.addAll(data.sortedBy { it.productId })
var currPos = 0
if (itemsList.size >= 4) {
adsList.forEach label@{ ad ->
if (itemsList.size > currPos + 1) {
itemsList.add(currPos, ad)
} else {
return@label
}
currPos += 5
}
}
return itemsList
}
private fun getAdsList(): List<Int> {
return listOf(R.drawable.ad_ex_2, R.drawable.ad_ex_1, R.drawable.ad_ex_3)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/LaunchActivity.kt
package com.vishalgaur.shoppingapp.ui
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.ui.loginSignup.LoginSignupActivity
class LaunchActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_launch)
setLaunchScreenTimeOut()
}
private fun setLaunchScreenTimeOut() {
Looper.myLooper()?.let {
Handler(it).postDelayed({
startPreferredActivity()
}, TIME_OUT)
}
}
private fun startPreferredActivity() {
val sessionManager = ShoppingAppSessionManager(this)
if (sessionManager.isLoggedIn()) {
launchHome(this)
finish()
} else {
val intent = Intent(this, LoginSignupActivity::class.java)
startActivity(intent)
finish()
}
}
companion object {
private const val TIME_OUT: Long = 1500
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/ShoppingAppSessionManager.kt
package com.vishalgaur.shoppingapp.data
import android.content.Context
import android.content.SharedPreferences
class ShoppingAppSessionManager(context: Context) {
var userSession: SharedPreferences =
context.getSharedPreferences("userSessionData", Context.MODE_PRIVATE)
var editor: SharedPreferences.Editor = userSession.edit()
fun createLoginSession(
id: String,
name: String,
mobile: String,
isRemOn: Boolean,
isSeller: Boolean
) {
editor.putBoolean(IS_LOGIN, true)
editor.putString(KEY_ID, id)
editor.putString(KEY_NAME, name)
editor.putString(KEY_MOBILE, mobile)
editor.putBoolean(KEY_REMEMBER_ME, isRemOn)
editor.putBoolean(KEY_IS_SELLER, isSeller)
editor.commit()
}
fun isUserSeller(): Boolean = userSession.getBoolean(KEY_IS_SELLER, false)
fun isRememberMeOn(): Boolean = userSession.getBoolean(KEY_REMEMBER_ME, false)
fun getPhoneNumber(): String? = userSession.getString(KEY_MOBILE, null)
fun getUserDataFromSession(): HashMap<String, String?> {
return hashMapOf(
KEY_ID to userSession.getString(KEY_ID, null),
KEY_NAME to userSession.getString(KEY_NAME, null),
KEY_MOBILE to userSession.getString(KEY_MOBILE, null)
)
}
fun getUserIdFromSession(): String? = userSession.getString(KEY_ID, null)
fun isLoggedIn(): Boolean = userSession.getBoolean(IS_LOGIN, false)
fun logoutFromSession() {
editor.clear()
editor.commit()
}
companion object {
private const val IS_LOGIN = "isLoggedIn"
private const val KEY_NAME = "userName"
private const val KEY_MOBILE = "userMobile"
private const val KEY_ID = "userId"
private const val KEY_REMEMBER_ME = "isRemOn"
private const val KEY_IS_SELLER = "isSeller"
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/utils/EmailMobileData.kt
package com.vishalgaur.shoppingapp.data.utils
data class EmailMobileData(
val emails: ArrayList<String> = ArrayList(),
val mobiles: ArrayList<String> = ArrayList()
)<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/viewModels/AddEditProductViewModelTest.kt
package com.vishalgaur.shoppingapp.viewModels
import android.net.Uri
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.core.net.toUri
import androidx.test.core.app.ApplicationProvider
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.getOrAwaitValue
import com.vishalgaur.shoppingapp.ui.AddProductViewErrors
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.notNullValue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AddEditProductViewModelTest {
private lateinit var addEditProductViewModel: AddEditProductViewModel
private lateinit var sessionManager: ShoppingAppSessionManager
private val userSeller = UserData(
"user1234selller",
"<NAME>",
"+919999988888",
"<EMAIL>",
"1234",
emptyList(),
emptyList(),
emptyList(),
"SELLER"
)
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun setUp() {
sessionManager = ShoppingAppSessionManager(ApplicationProvider.getApplicationContext())
sessionManager.createLoginSession(
userSeller.userId,
userSeller.name,
userSeller.mobile,
false,
true
)
addEditProductViewModel =
AddEditProductViewModel(ApplicationProvider.getApplicationContext())
}
@Test
fun setCategory_Shoes() {
addEditProductViewModel.setCategory("Shoes")
val result = addEditProductViewModel.selectedCategory.getOrAwaitValue()
assertThat(result, `is`("Shoes"))
}
@Test
fun setIsEdit_true() {
addEditProductViewModel.setIsEdit(true)
val result = addEditProductViewModel.isEdit.getOrAwaitValue()
assertThat(result, `is`(true))
}
@Test
fun setIsEdit_false() {
addEditProductViewModel.setIsEdit(false)
val result = addEditProductViewModel.isEdit.getOrAwaitValue()
assertThat(result, `is`(false))
}
@Test
fun submitProduct_noData_returnsEmptyError() {
addEditProductViewModel.setIsEdit(false)
val name = ""
val price = null
val mrp = null
val desc = ""
val sizes = emptyList<Int>()
val colors = emptyList<String>()
val imgList = emptyList<Uri>()
addEditProductViewModel.submitProduct(name, price, mrp, desc, sizes, colors, imgList)
val result = addEditProductViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(AddProductViewErrors.EMPTY))
}
@Test
fun submitProduct_invalidPrice_returnsPriceError() {
addEditProductViewModel.setIsEdit(false)
val name = "vwsf"
val mrp = 125.0
val price = 0.0
val desc = "crw rewg"
val sizes = listOf(5, 6)
val colors = listOf("red", "blue")
val imgList = listOf("ffsd".toUri(), "sws".toUri())
addEditProductViewModel.submitProduct(name, price, mrp, desc, sizes, colors, imgList)
val result = addEditProductViewModel.errorStatus.getOrAwaitValue()
assertThat(result, `is`(AddProductViewErrors.ERR_PRICE_0))
}
@Test
fun submitProduct_allValid_returnsNoError() {
addEditProductViewModel.setIsEdit(false)
addEditProductViewModel.setCategory("Shoes")
val name = "vwsf"
val mrp = 125.0
val price = 100.0
val desc = "crw rewg"
val sizes = listOf(5, 6)
val colors = listOf("red", "blue")
val imgList = listOf("ffsd".toUri(), "sws".toUri())
addEditProductViewModel.submitProduct(name, price, mrp, desc, sizes, colors, imgList)
val result = addEditProductViewModel.errorStatus.getOrAwaitValue()
val resultPro = addEditProductViewModel.newProductData.getOrAwaitValue()
assertThat(result, `is`(AddProductViewErrors.NONE))
assertThat(resultPro, `is`(notNullValue()))
assertThat(resultPro.name, `is`("vwsf"))
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/repository/ProductsRepoInterface.kt
package com.vishalgaur.shoppingapp.data.source.repository
import android.net.Uri
import androidx.lifecycle.LiveData
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
interface ProductsRepoInterface {
suspend fun refreshProducts(): StoreDataStatus?
fun observeProducts(): LiveData<Result<List<Product>>?>
fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?>
suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>>
suspend fun getProductById(productId: String, forceUpdate: Boolean = false): Result<Product>
suspend fun insertProduct(newProduct: Product): Result<Boolean>
suspend fun insertImages(imgList: List<Uri>): List<String>
suspend fun updateProduct(product: Product): Result<Boolean>
suspend fun updateImages(newList: List<Uri>, oldList: List<String>): List<String>
suspend fun deleteProductById(productId: String): Result<Boolean>
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/FavoritesFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentFavoritesBinding
import com.vishalgaur.shoppingapp.ui.RecyclerViewPaddingItemDecoration
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
private const val TAG = "FavoritesFragment"
class FavoritesFragment : Fragment() {
private lateinit var binding: FragmentFavoritesBinding
private val viewModel: HomeViewModel by activityViewModels()
private lateinit var productsAdapter: LikedProductAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentFavoritesBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
private fun setViews() {
viewModel.setDataLoading()
viewModel.getLikedProducts()
binding.favTopAppBar.topAppBar.title = "Favorite Products"
binding.favTopAppBar.topAppBar.setNavigationOnClickListener {
findNavController().navigateUp()
}
binding.favEmptyTextView.visibility = View.GONE
if (context != null) {
val proList = viewModel.likedProducts.value ?: emptyList()
productsAdapter = LikedProductAdapter(proList, requireContext())
productsAdapter.onClickListener = object : LikedProductAdapter.OnClickListener {
override fun onClick(productData: Product) {
Log.d(TAG, "Product: ${productData.productId} clicked")
findNavController().navigate(
R.id.action_favoritesFragment_to_productDetailsFragment,
bundleOf("productId" to productData.productId)
)
}
override fun onDeleteClick(productId: String) {
viewModel.toggleLikeByProductId(productId)
}
}
binding.favProductsRecyclerView.apply {
val itemDecoration = RecyclerViewPaddingItemDecoration(requireContext())
if (itemDecorationCount == 0) {
addItemDecoration(itemDecoration)
}
}
}
}
private fun setObservers() {
viewModel.dataStatus.observe(viewLifecycleOwner) { status ->
if (status == StoreDataStatus.LOADING) {
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
binding.favEmptyTextView.visibility = View.GONE
} else if (status != null) {
viewModel.likedProducts.observe(viewLifecycleOwner) {
if (it.isNotEmpty()) {
productsAdapter.data = viewModel.likedProducts.value!!
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
productsAdapter.data = it
binding.favProductsRecyclerView.adapter = productsAdapter
binding.favProductsRecyclerView.adapter?.apply {
notifyDataSetChanged()
}
} else if (it.isEmpty()) {
binding.favEmptyTextView.visibility = View.VISIBLE
binding.favProductsRecyclerView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
}
}
}
}
}
}<file_sep>/app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/repository/ProductsRepositoryTest.kt
package com.vishalgaur.shoppingapp.data.source.repository
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.core.net.toUri
import androidx.test.espresso.matcher.ViewMatchers.assertThat
import com.vishalgaur.shoppingapp.ERR_UPLOAD
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.source.FakeProductsDataSource
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.getOrAwaitValue
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.test.runBlockingTest
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.greaterThan
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class ProductsRepositoryTest {
private val pro1 = Product(
"pro-owner1-shoe-101",
"Shoe Name 101",
"owner1",
"some description",
"Shoes",
250.0,
300.0,
listOf(5, 6, 7, 8),
listOf("Red", "Blue"),
listOf("http://image-ref-uri/shoe-101-01.jpg", "http://image-ref-uri/-shoe-101-02.jpg"),
2.5
)
private val pro2 = Product(
"pro-owner1-slipper-101",
"Slipper Name 101",
"owner1",
"some description",
"Slippers",
50.0,
80.0,
listOf(6, 7, 8),
listOf("Black", "Blue"),
listOf(
"http://image-ref-uri/-slipper-101-01.jpg",
"http://image-ref-uri/-slipper-101-02.jpg"
),
4.0
)
private val pro3 = Product(
"pro-owner1-shoe-102",
"Shoe Name 102",
"owner2",
"some description",
"Shoes",
450.0,
600.0,
listOf(4, 5, 7, 8, 10),
listOf("Red", "Blue", "White"),
listOf("http://image-ref-uri/-shoe-102-01.jpg", "http://image-ref-uri/-shoe-102-02.jpg"),
3.5
)
private lateinit var productsLocalDataSource: FakeProductsDataSource
private lateinit var productsRemoteDataSource: FakeProductsDataSource
// class under test
private lateinit var productsRepository: ProductsRepository
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Before
fun createRepository() {
productsLocalDataSource = FakeProductsDataSource(mutableListOf())
productsRemoteDataSource = FakeProductsDataSource(mutableListOf(pro1, pro3))
productsRepository = ProductsRepository(productsRemoteDataSource, productsLocalDataSource)
}
@Test
fun getProductsById_invalidId_returnsError() = runBlockingTest {
val resultRes = productsRepository.getProductById("invalidId", false)
if (resultRes is Result.Success)
assert(false)
else if (resultRes is Result.Error) {
assertEquals(resultRes.exception.message, "Product Not Found")
}
}
@Test
fun getProductsById_validId_returnsProduct() = runBlockingTest {
productsRepository.insertProduct(pro1)
val resultRes = productsRepository.getProductById(pro1.productId, false)
if (resultRes is Result.Success) {
assertThat(resultRes.data, `is`(pro1))
} else if (resultRes is Result.Error) {
assert(false)
}
}
@Test
fun insertProduct_returnsSuccess() = runBlockingTest {
val insertRes = productsRepository.insertProduct(pro1)
if (insertRes is Result.Success) {
assertThat(insertRes.data, `is`(true))
} else {
assert(false)
}
}
@Test
fun insertImages_returnsSuccess() = runBlockingTest {
val result = productsRepository.insertImages(pro1.images.map { it.toUri() })
assertThat(result.size, `is`(pro1.images.size))
}
@Test
fun insertImages_invalidImages_returnsError() = runBlockingTest {
val result =
productsRepository.insertImages(listOf("http://image-ref-uri/dwoeiovnwi-invalidinvalidinvalid/weoifhowf".toUri()))
assertThat(result[0], `is`(ERR_UPLOAD))
}
@Test
fun updateProduct_returnsSuccess() = runBlockingTest {
productsRepository.insertProduct(pro2)
val updatedPro = pro2
updatedPro.availableSizes = listOf(5, 6, 10, 12)
val insertRes = productsRepository.updateProduct(updatedPro)
if (insertRes is Result.Success) {
assertThat(insertRes.data, `is`(true))
} else {
assert(false)
}
}
@Test
fun updateImages_returnsList() = runBlockingTest {
val oldList = productsRepository.insertImages(pro1.images.map { it.toUri() })
val result = productsRepository.updateImages(pro3.images.map { it.toUri() }, oldList)
assertThat(result.size, `is`(pro3.images.size))
}
@Test
fun updateImages_invalidImage_returnsError() = runBlockingTest {
val oldList = productsRepository.insertImages(pro1.images.map { it.toUri() })
val newList = oldList.toMutableList()
newList[0] = "http://csifduoskjgn/invalidinvalidinvalid/wehoiw"
val result = productsRepository.updateImages(newList.map { it.toUri() }, oldList)
assertThat(result[0], `is`(ERR_UPLOAD))
}
@Test
fun deleteProductById_returnsSuccess() = runBlockingTest {
productsRepository.insertProduct(pro1)
productsRepository.insertProduct(pro2)
val result = productsRepository.deleteProductById(pro1.productId)
assert(result is Result.Success)
}
@Test
fun deleteProductById_invalidId_returnsError() = runBlockingTest {
productsRepository.insertProduct(pro1)
productsRepository.insertProduct(pro2)
val result = productsRepository.deleteProductById(pro3.productId)
assert(result is Result.Error)
}
@Test
fun refreshProducts_returnsSuccess() = runBlockingTest {
val result = productsRepository.refreshProducts()
assertThat(result, `is`(StoreDataStatus.DONE))
}
@Test
fun observeProducts_noData_returnsNoData() = runBlockingTest {
productsLocalDataSource.deleteAllProducts()
val result = productsRepository.observeProducts().getOrAwaitValue()
if (result is Result.Success) {
assertThat(result.data.size, `is`(0))
} else {
assert(false)
}
}
@Test
fun observeProducts_hasData_returnsSuccessWithData() = runBlockingTest {
val initialValue = productsRepository.observeProducts().getOrAwaitValue()
val insertRes = async { productsRepository.insertProduct(pro3) }
insertRes.await()
val refreshRes = async { productsRepository.refreshProducts() }
assertThat(refreshRes.await(), `is`(StoreDataStatus.DONE))
val newValue = productsRepository.observeProducts().getOrAwaitValue()
assertNotEquals(initialValue.toString(), newValue.toString())
if (initialValue is Result.Success) {
assertThat(initialValue.data.size, `is`(0))
} else {
assert(false)
}
if (newValue is Result.Success) {
assertThat(newValue.data.size, `is`(greaterThan(0)))
} else {
assert(false)
}
}
@Test
fun observeProductsByOwner_noData_returnsNoData() = runBlockingTest {
productsLocalDataSource.deleteAllProducts()
val result = productsRepository.observeProductsByOwner(pro1.owner).getOrAwaitValue()
if (result is Result.Success) {
assertThat(result.data.size, `is`(0))
} else {
assert(false)
}
}
@Test
fun observeProductsByOwner_hasData_returnsSuccessWithData() = runBlockingTest {
val initialValue = productsRepository.observeProductsByOwner(pro3.owner).getOrAwaitValue()
val insertRes = async { productsRepository.insertProduct(pro3) }
insertRes.await()
val refreshRes = async { productsRepository.refreshProducts() }
assertThat(refreshRes.await(), `is`(StoreDataStatus.DONE))
val newValue = productsRepository.observeProductsByOwner(pro3.owner).getOrAwaitValue()
assertNotEquals(initialValue.toString(), newValue.toString())
if (initialValue is Result.Success) {
assertThat(initialValue.data.size, `is`(0))
} else {
assert(false)
}
if (newValue is Result.Success) {
assertThat(newValue.data.size, `is`(greaterThan(0)))
} else {
assert(false)
}
}
@Test
fun getAllProductsByOwner_noData_returnsNoData() = runBlockingTest {
productsLocalDataSource.deleteAllProducts()
val result = productsRepository.getAllProductsByOwner(pro1.owner)
if (result is Result.Success) {
assertThat(result.data.size, `is`(0))
} else {
assert(false)
}
}
@Test
fun getAllProductsByOwner_hasData_returnsData() = runBlockingTest {
productsRepository.refreshProducts()
val result = productsRepository.getAllProductsByOwner(pro1.owner)
if (result is Result.Success) {
assertThat(result.data.size, `is`(greaterThan(0)))
} else {
assert(false)
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/ui/home/AddressFragment.kt
package com.vishalgaur.shoppingapp.ui.home
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.vishalgaur.shoppingapp.R
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.databinding.FragmentAddressBinding
import com.vishalgaur.shoppingapp.viewModels.HomeViewModel
private const val TAG = "AddressFragment"
class AddressFragment : Fragment() {
private lateinit var binding: FragmentAddressBinding
private lateinit var addressAdapter: AddressAdapter
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAddressBinding.inflate(layoutInflater)
setViews()
setObservers()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.getUserAddresses()
}
private fun setViews() {
binding.addressAppBar.topAppBar.title = "Address"
binding.addressAppBar.topAppBar.setNavigationOnClickListener { findNavController().navigateUp() }
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.addressAddBtn.visibility = View.GONE
binding.addressAddBtn.setOnClickListener {
navigateToAddEditAddress(false)
}
binding.addressEmptyTextView.visibility = View.GONE
if (context != null) {
val addressList = viewModel.userAddresses.value ?: emptyList()
addressAdapter = AddressAdapter(requireContext(), addressList, false)
addressAdapter.onClickListener = object : AddressAdapter.OnClickListener {
override fun onEditClick(addressId: String) {
Log.d(TAG, "onEditAddress: initiated")
navigateToAddEditAddress(true, addressId)
}
override fun onDeleteClick(addressId: String) {
Log.d(TAG, "onDeleteAddress: initiated")
showDeleteDialog(addressId)
}
}
binding.addressAddressesRecyclerView.adapter = addressAdapter
}
}
private fun setObservers() {
viewModel.dataStatus.observe(viewLifecycleOwner) { status ->
when (status) {
StoreDataStatus.LOADING -> {
binding.addressEmptyTextView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.showAnimationBehavior
}
else -> {
binding.addressAddBtn.visibility = View.VISIBLE
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
}
}
if (status != null && status != StoreDataStatus.LOADING) {
viewModel.userAddresses.observe(viewLifecycleOwner) { addressList ->
if (addressList.isNotEmpty()) {
addressAdapter.data = addressList
binding.addressAddressesRecyclerView.adapter = addressAdapter
binding.addressAddressesRecyclerView.adapter?.notifyDataSetChanged()
} else if (addressList.isEmpty()) {
binding.addressAddressesRecyclerView.visibility = View.GONE
binding.loaderLayout.loaderFrameLayout.visibility = View.GONE
binding.loaderLayout.circularLoader.hideAnimationBehavior
binding.addressEmptyTextView.visibility = View.VISIBLE
}
}
binding.addressAddBtn.visibility = View.VISIBLE
}
}
}
private fun showDeleteDialog(addressId: String) {
context?.let {
MaterialAlertDialogBuilder(it)
.setTitle(getString(R.string.delete_dialog_title_text))
.setMessage(getString(R.string.delete_address_message_text))
.setNeutralButton(getString(R.string.pro_cat_dialog_cancel_btn)) { dialog, _ ->
dialog.cancel()
}
.setPositiveButton(getString(R.string.delete_dialog_delete_btn_text)) { dialog, _ ->
viewModel.deleteAddress(addressId)
dialog.cancel()
}
.show()
}
}
private fun navigateToAddEditAddress(isEdit: Boolean, addressId: String? = null) {
findNavController().navigate(
R.id.action_addressFragment_to_addEditAddressFragment,
bundleOf("isEdit" to isEdit, "addressId" to addressId)
)
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/viewModels/OrderViewModel.kt
package com.vishalgaur.shoppingapp.viewModels
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.vishalgaur.shoppingapp.ShoppingApplication
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.ShoppingAppSessionManager
import com.vishalgaur.shoppingapp.data.UserData
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import com.vishalgaur.shoppingapp.getRandomString
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import java.util.*
private const val TAG = "OrderViewModel"
class OrderViewModel(application: Application) : AndroidViewModel(application) {
private val sessionManager = ShoppingAppSessionManager(application.applicationContext)
private val currentUser = sessionManager.getUserIdFromSession()
private val authRepository = (application as ShoppingApplication).authRepository
private val productsRepository = (application as ShoppingApplication).productsRepository
private val _userAddresses = MutableLiveData<List<UserData.Address>>()
val userAddresses: LiveData<List<UserData.Address>> get() = _userAddresses
private val _userLikes = MutableLiveData<List<String>>()
val userLikes: LiveData<List<String>> get() = _userLikes
private val _cartItems = MutableLiveData<List<UserData.CartItem>>()
val cartItems: LiveData<List<UserData.CartItem>> get() = _cartItems
private val _priceList = MutableLiveData<Map<String, Double>>()
val priceList: LiveData<Map<String, Double>> get() = _priceList
private val _cartProducts = MutableLiveData<List<Product>>()
val cartProducts: LiveData<List<Product>> get() = _cartProducts
private val _dataStatus = MutableLiveData<StoreDataStatus>()
val dataStatus: LiveData<StoreDataStatus> get() = _dataStatus
private val _orderStatus = MutableLiveData<StoreDataStatus>()
val orderStatus: LiveData<StoreDataStatus> get() = _orderStatus
private val _selectedAddress = MutableLiveData<String>()
private val _selectedPaymentMethod = MutableLiveData<String>()
private val newOrderData = MutableLiveData<UserData.OrderItem>()
init {
viewModelScope.launch {
getUserLikes()
}
}
fun getCartItems() {
Log.d(TAG, "Getting Cart Items")
_dataStatus.value = StoreDataStatus.LOADING
viewModelScope.launch {
val deferredRes = async {
authRepository.hardRefreshUserData()
authRepository.getUserData(currentUser!!)
}
val userRes = deferredRes.await()
if (userRes is Success) {
val uData = userRes.data
if (uData != null) {
_cartItems.value = uData.cart
val priceRes = async { getAllProductsInCart() }
priceRes.await()
Log.d(TAG, "Getting Cart Items: Success ${_priceList.value}")
} else {
_cartItems.value = emptyList()
_dataStatus.value = StoreDataStatus.ERROR
Log.d(TAG, "Getting Cart Items: User Not Found")
}
} else {
_cartItems.value = emptyList()
_dataStatus.value = StoreDataStatus.ERROR
Log.d(TAG, "Getting Cart Items: Error Occurred")
}
}
}
fun getUserAddresses() {
Log.d(TAG, "Getting Addresses")
_dataStatus.value = StoreDataStatus.LOADING
viewModelScope.launch {
val res = authRepository.getAddressesByUserId(currentUser!!)
if (res is Success) {
_userAddresses.value = res.data ?: emptyList()
_dataStatus.value = StoreDataStatus.DONE
Log.d(TAG, "Getting Addresses: Success")
} else {
_userAddresses.value = emptyList()
_dataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "Getting Addresses: Error Occurred, ${res.exception.message}")
}
}
}
fun getUserLikes() {
Log.d(TAG, "Getting Likes")
// _dataStatus.value = StoreDataStatus.LOADING
viewModelScope.launch {
val res = authRepository.getLikesByUserId(currentUser!!)
if (res is Success) {
val data = res.data ?: emptyList()
if (data[0] != "") {
_userLikes.value = data
} else {
_userLikes.value = emptyList()
}
_dataStatus.value = StoreDataStatus.DONE
Log.d(TAG, "Getting Likes: Success")
} else {
_userLikes.value = emptyList()
_dataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "Getting Likes: Error Occurred, ${res.exception.message}")
}
}
}
fun deleteAddress(addressId: String) {
viewModelScope.launch {
val delRes = async { authRepository.deleteAddressById(addressId, currentUser!!) }
when (val res = delRes.await()) {
is Success -> {
Log.d(TAG, "onDeleteAddress: Success")
val addresses = _userAddresses.value?.toMutableList()
addresses?.let {
val pos =
addresses.indexOfFirst { address -> address.addressId == addressId }
if (pos >= 0)
it.removeAt(pos)
_userAddresses.value = it
}
}
is Error -> Log.d(TAG, "onDeleteAddress: Error, ${res.exception}")
else -> Log.d(TAG, "onDeleteAddress: Some error occurred!")
}
}
}
fun getItemsPriceTotal(): Double {
var totalPrice = 0.0
_priceList.value?.forEach { (itemId, price) ->
totalPrice += price * (_cartItems.value?.find { it.itemId == itemId }?.quantity ?: 1)
}
return totalPrice
}
fun toggleLikeProduct(productId: String) {
Log.d(TAG, "toggling Like")
viewModelScope.launch {
// _dataStatus.value = StoreDataStatus.LOADING
val isLiked = _userLikes.value?.contains(productId) == true
val allLikes = _userLikes.value?.toMutableList() ?: mutableListOf()
val deferredRes = async {
if (isLiked) {
authRepository.removeProductFromLikes(productId, currentUser!!)
} else {
authRepository.insertProductToLikes(productId, currentUser!!)
}
}
val res = deferredRes.await()
if (res is Success) {
if (isLiked) {
allLikes.remove(productId)
} else {
allLikes.add(productId)
}
_userLikes.value = allLikes
_dataStatus.value = StoreDataStatus.DONE
} else {
_dataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "onUpdateQuantity: Error Occurred: ${res.exception.message}")
}
}
}
fun getItemsCount(): Int {
var totalCount = 0
_cartItems.value?.forEach {
totalCount += it.quantity
}
return totalCount
}
fun setQuantityOfItem(itemId: String, value: Int) {
viewModelScope.launch {
// _dataStatus.value = StoreDataStatus.LOADING
var cartList: MutableList<UserData.CartItem>
_cartItems.value?.let { items ->
val item = items.find { it.itemId == itemId }
val itemPos = items.indexOfFirst { it.itemId == itemId }
cartList = items.toMutableList()
if (item != null) {
item.quantity = item.quantity + value
val deferredRes = async {
authRepository.updateCartItemByUserId(item, currentUser!!)
}
val res = deferredRes.await()
if (res is Success) {
cartList[itemPos] = item
_cartItems.value = cartList
_dataStatus.value = StoreDataStatus.DONE
} else {
_dataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "onUpdateQuantity: Error Occurred: ${res.exception.message}")
}
}
}
}
}
fun deleteItemFromCart(itemId: String) {
viewModelScope.launch {
// _dataStatus.value = StoreDataStatus.LOADING
var cartList: MutableList<UserData.CartItem>
_cartItems.value?.let { items ->
val itemPos = items.indexOfFirst { it.itemId == itemId }
cartList = items.toMutableList()
val deferredRes = async {
authRepository.deleteCartItemByUserId(itemId, currentUser!!)
}
val res = deferredRes.await()
if (res is Success) {
cartList.removeAt(itemPos)
_cartItems.value = cartList
val priceRes = async { getAllProductsInCart() }
priceRes.await()
} else {
_dataStatus.value = StoreDataStatus.ERROR
if (res is Error)
Log.d(TAG, "onUpdateQuantity: Error Occurred: ${res.exception.message}")
}
}
}
}
fun setSelectedAddress(addressId: String) {
_selectedAddress.value = addressId
}
fun setSelectedPaymentMethod(method: String) {
_selectedPaymentMethod.value = method
}
fun finalizeOrder() {
_orderStatus.value = StoreDataStatus.LOADING
val deliveryAddress =
_userAddresses.value?.find { it.addressId == _selectedAddress.value }
val paymentMethod = _selectedPaymentMethod.value
val currDate = Date()
val orderId = getRandomString(6, currDate.time.toString(), 1)
val items = _cartItems.value
val itemPrices = _priceList.value
val shippingCharges = 0.0
if (deliveryAddress != null && paymentMethod != null && !items.isNullOrEmpty() && !itemPrices.isNullOrEmpty()) {
val newOrder = UserData.OrderItem(
orderId,
currentUser!!,
items,
itemPrices,
deliveryAddress,
shippingCharges,
paymentMethod,
currDate,
)
newOrderData.value = newOrder
insertOrder()
} else {
Log.d(TAG, "orFinalizeOrder: Error, data null or empty")
_orderStatus.value = StoreDataStatus.ERROR
}
}
private fun insertOrder() {
viewModelScope.launch {
if (newOrderData.value != null) {
_orderStatus.value = StoreDataStatus.LOADING
val deferredRes = async {
authRepository.placeOrder(newOrderData.value!!, currentUser!!)
}
val res = deferredRes.await()
if (res is Success) {
Log.d(TAG, "onInsertOrder: Success")
_cartItems.value = emptyList()
_cartProducts.value = emptyList()
_priceList.value = emptyMap()
_orderStatus.value = StoreDataStatus.DONE
} else {
_orderStatus.value = StoreDataStatus.ERROR
if (res is Error) {
Log.d(TAG, "onInsertOrder: Error, ${res.exception}")
}
}
} else {
Log.d(TAG, "orInsertOrder: Error, newProduct Null")
_orderStatus.value = StoreDataStatus.ERROR
}
}
}
private suspend fun getAllProductsInCart() {
viewModelScope.launch {
// _dataStatus.value = StoreDataStatus.LOADING
val priceMap = mutableMapOf<String, Double>()
val proList = mutableListOf<Product>()
var res = true
_cartItems.value?.let { itemList ->
itemList.forEach label@{ item ->
val productDeferredRes = async {
productsRepository.getProductById(item.productId, true)
}
val proRes = productDeferredRes.await()
if (proRes is Success) {
val proData = proRes.data
proList.add(proData)
priceMap[item.itemId] = proData.price
} else {
res = false
return@label
}
}
}
_priceList.value = priceMap
_cartProducts.value = proList
if (!res) {
_dataStatus.value = StoreDataStatus.ERROR
} else {
_dataStatus.value = StoreDataStatus.DONE
}
}
}
}<file_sep>/app/src/main/java/com/vishalgaur/shoppingapp/data/source/local/UserDao.kt
package com.vishalgaur.shoppingapp.data.source.local
import androidx.room.*
import com.vishalgaur.shoppingapp.data.UserData
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(uData: UserData)
@Query("SELECT * FROM users WHERE userId = :userId")
suspend fun getById(userId: String): UserData?
@Query("SELECT * FROM users WHERE mobile = :mobile")
suspend fun getByMobile(mobile: String): UserData?
@Update(entity = UserData::class)
suspend fun updateUser(obj: UserData)
@Query("DELETE FROM users")
suspend fun clear()
} | 8ec084549581ae16dec7d58bcaf1d3db68c5a344 | [
"Markdown",
"Kotlin"
] | 82 | Kotlin | SARATH365/shopping-android-app | bfed51a85075b504d2fb242eb37bf365dd1a6392 | 275981bcda66987071533d5f242da90b4b124614 | |
refs/heads/master | <repo_name>Sivasathivel/RugbyUnionScoreCard<file_sep>/app/src/main/java/com/example/android/rugbyunionscorecard/MainActivity.java
package com.example.android.rugbyunionscorecard;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayScores();
}
//Global Variable Declaration
int teamAScore = 0;
int teamBScore = 0;
private void displayScores(){
TextView text = (TextView)findViewById(R.id.teamA_score);
text.setText("" + teamAScore);
text = (TextView)findViewById(R.id.teamB_score);
text.setText("" + teamBScore);
}
public void reset(View view){
teamAScore = 0;
teamBScore = 0;
displayScores();
}
public void updateTry(View view){
String parent_id = getResources().getResourceEntryName(((View)view.getParent()).getId());
switch (parent_id){
case "teamA":
teamAScore += 5;
break;
case "teamB":
teamBScore += 5;
break;
default:
break;
}
displayScores();
}
public void updateKick(View view){
String parent_id = getResources().getResourceEntryName(((View)view.getParent()).getId());
switch (parent_id){
case "teamA":
teamAScore += 2;
break;
case "teamB":
teamBScore += 2;
break;
default:
break;
}
displayScores();
}
public void updatePenalty(View view){
String parent_id = getResources().getResourceEntryName(((View)view.getParent()).getId());
switch (parent_id){
case "teamA":
teamAScore += 3;
break;
case "teamB":
teamBScore += 3;
break;
default:
break;
}
displayScores();
}
public void updateDrop(View view){
String parent_id = getResources().getResourceEntryName(((View)view.getParent()).getId());
switch (parent_id){
case "teamA":
teamAScore += 3;
break;
case "teamB":
teamBScore += 3;
break;
default:
break;
}
displayScores();
}
}
| c383c6f4195e22610c3ba943f3c084867e3850f8 | [
"Java"
] | 1 | Java | Sivasathivel/RugbyUnionScoreCard | 9be7a73aac506cb93e423dc57dac0e6c54de47e1 | cab683d9a9800ac748f41c91f0324aa7f27dddf7 | |
refs/heads/master | <file_sep>SELECT Manufacturers.ManufacturerName, SUM(StoredProducts.Count) FROM StoredProducts
INNER JOIN Products ON Products.ProductId = StoredProducts.ProductId
INNER JOIN Manufacturers ON Manufacturers.ManufacturerId =Products.ManufacturerId
GROUP BY Manufacturers.ManufacturerName | d1df6840282a4282bd882f383dcc69b81d47bb4e | [
"SQL"
] | 1 | SQL | DmytroKryvovychev/DB_Homework_Kryvovychev | 32ace11f89d61299296d9631ad1f57fe791a6eec | 7d595d533430bfb6121de64016fb35fd7d5edebf | |
refs/heads/master | <file_sep>/**
* Spring Security configuration.
*/
package org.codingblog.security;
<file_sep>package org.codingblog.web.rest;
import org.codingblog.CodeBlogApp;
import org.codingblog.domain.Gallery;
import org.codingblog.repository.GalleryRepository;
import org.codingblog.service.GalleryService;
import org.codingblog.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;
import static org.codingblog.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the GalleryResource REST controller.
*
* @see GalleryResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CodeBlogApp.class)
public class GalleryResourceIntTest {
private static final Long DEFAULT_USER_ID = 1L;
private static final Long UPDATED_USER_ID = 2L;
private static final String DEFAULT_LABEL_NAME = "AAAAAAAAAA";
private static final String UPDATED_LABEL_NAME = "BBBBBBBBBB";
private static final String DEFAULT_CATEGORY = "AAAAAAAAAA";
private static final String UPDATED_CATEGORY = "BBBBBBBBBB";
private static final String DEFAULT_IMG_URL = "AAAAAAAAAA";
private static final String UPDATED_IMG_URL = "BBBBBBBBBB";
private static final String DEFAULT_SHORT_MSG = "AAAAAAAAAA";
private static final String UPDATED_SHORT_MSG = "BBBBBBBBBB";
private static final ZonedDateTime DEFAULT_CREATE_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_CREATE_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final Integer DEFAULT_RESOURCE_TYPE = 1;
private static final Integer UPDATED_RESOURCE_TYPE = 2;
@Autowired
private GalleryRepository galleryRepository;
@Autowired
private GalleryService galleryService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restGalleryMockMvc;
private Gallery gallery;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
GalleryResource galleryResource = new GalleryResource(galleryService);
this.restGalleryMockMvc = MockMvcBuilders.standaloneSetup(galleryResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Gallery createEntity(EntityManager em) {
Gallery gallery = new Gallery()
.userId(DEFAULT_USER_ID)
.labelName(DEFAULT_LABEL_NAME)
.category(DEFAULT_CATEGORY)
.imgUrl(DEFAULT_IMG_URL)
.shortMsg(DEFAULT_SHORT_MSG)
.createTime(DEFAULT_CREATE_TIME)
.resourceType(DEFAULT_RESOURCE_TYPE);
return gallery;
}
@Before
public void initTest() {
gallery = createEntity(em);
}
@Test
@Transactional
public void createGallery() throws Exception {
int databaseSizeBeforeCreate = galleryRepository.findAll().size();
// Create the Gallery
restGalleryMockMvc.perform(post("/api/galleries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(gallery)))
.andExpect(status().isCreated());
// Validate the Gallery in the database
List<Gallery> galleryList = galleryRepository.findAll();
assertThat(galleryList).hasSize(databaseSizeBeforeCreate + 1);
Gallery testGallery = galleryList.get(galleryList.size() - 1);
assertThat(testGallery.getUserId()).isEqualTo(DEFAULT_USER_ID);
assertThat(testGallery.getLabelName()).isEqualTo(DEFAULT_LABEL_NAME);
assertThat(testGallery.getCategory()).isEqualTo(DEFAULT_CATEGORY);
assertThat(testGallery.getImgUrl()).isEqualTo(DEFAULT_IMG_URL);
assertThat(testGallery.getShortMsg()).isEqualTo(DEFAULT_SHORT_MSG);
assertThat(testGallery.getCreateTime()).isEqualTo(DEFAULT_CREATE_TIME);
assertThat(testGallery.getResourceType()).isEqualTo(DEFAULT_RESOURCE_TYPE);
}
@Test
@Transactional
public void createGalleryWithExistingId() throws Exception {
int databaseSizeBeforeCreate = galleryRepository.findAll().size();
// Create the Gallery with an existing ID
gallery.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restGalleryMockMvc.perform(post("/api/galleries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(gallery)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<Gallery> galleryList = galleryRepository.findAll();
assertThat(galleryList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllGalleries() throws Exception {
// Initialize the database
galleryRepository.saveAndFlush(gallery);
// Get all the galleryList
restGalleryMockMvc.perform(get("/api/galleries?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(gallery.getId().intValue())))
.andExpect(jsonPath("$.[*].userId").value(hasItem(DEFAULT_USER_ID.intValue())))
.andExpect(jsonPath("$.[*].labelName").value(hasItem(DEFAULT_LABEL_NAME.toString())))
.andExpect(jsonPath("$.[*].category").value(hasItem(DEFAULT_CATEGORY.toString())))
.andExpect(jsonPath("$.[*].imgUrl").value(hasItem(DEFAULT_IMG_URL.toString())))
.andExpect(jsonPath("$.[*].shortMsg").value(hasItem(DEFAULT_SHORT_MSG.toString())))
.andExpect(jsonPath("$.[*].createTime").value(hasItem(sameInstant(DEFAULT_CREATE_TIME))))
.andExpect(jsonPath("$.[*].resourceType").value(hasItem(DEFAULT_RESOURCE_TYPE)));
}
@Test
@Transactional
public void getGallery() throws Exception {
// Initialize the database
galleryRepository.saveAndFlush(gallery);
// Get the gallery
restGalleryMockMvc.perform(get("/api/galleries/{id}", gallery.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(gallery.getId().intValue()))
.andExpect(jsonPath("$.userId").value(DEFAULT_USER_ID.intValue()))
.andExpect(jsonPath("$.labelName").value(DEFAULT_LABEL_NAME.toString()))
.andExpect(jsonPath("$.category").value(DEFAULT_CATEGORY.toString()))
.andExpect(jsonPath("$.imgUrl").value(DEFAULT_IMG_URL.toString()))
.andExpect(jsonPath("$.shortMsg").value(DEFAULT_SHORT_MSG.toString()))
.andExpect(jsonPath("$.createTime").value(sameInstant(DEFAULT_CREATE_TIME)))
.andExpect(jsonPath("$.resourceType").value(DEFAULT_RESOURCE_TYPE));
}
@Test
@Transactional
public void getNonExistingGallery() throws Exception {
// Get the gallery
restGalleryMockMvc.perform(get("/api/galleries/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateGallery() throws Exception {
// Initialize the database
galleryService.save(gallery);
int databaseSizeBeforeUpdate = galleryRepository.findAll().size();
// Update the gallery
Gallery updatedGallery = galleryRepository.findOne(gallery.getId());
updatedGallery
.userId(UPDATED_USER_ID)
.labelName(UPDATED_LABEL_NAME)
.category(UPDATED_CATEGORY)
.imgUrl(UPDATED_IMG_URL)
.shortMsg(UPDATED_SHORT_MSG)
.createTime(UPDATED_CREATE_TIME)
.resourceType(UPDATED_RESOURCE_TYPE);
restGalleryMockMvc.perform(put("/api/galleries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedGallery)))
.andExpect(status().isOk());
// Validate the Gallery in the database
List<Gallery> galleryList = galleryRepository.findAll();
assertThat(galleryList).hasSize(databaseSizeBeforeUpdate);
Gallery testGallery = galleryList.get(galleryList.size() - 1);
assertThat(testGallery.getUserId()).isEqualTo(UPDATED_USER_ID);
assertThat(testGallery.getLabelName()).isEqualTo(UPDATED_LABEL_NAME);
assertThat(testGallery.getCategory()).isEqualTo(UPDATED_CATEGORY);
assertThat(testGallery.getImgUrl()).isEqualTo(UPDATED_IMG_URL);
assertThat(testGallery.getShortMsg()).isEqualTo(UPDATED_SHORT_MSG);
assertThat(testGallery.getCreateTime()).isEqualTo(UPDATED_CREATE_TIME);
assertThat(testGallery.getResourceType()).isEqualTo(UPDATED_RESOURCE_TYPE);
}
@Test
@Transactional
public void updateNonExistingGallery() throws Exception {
int databaseSizeBeforeUpdate = galleryRepository.findAll().size();
// Create the Gallery
// If the entity doesn't have an ID, it will be created instead of just being updated
restGalleryMockMvc.perform(put("/api/galleries")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(gallery)))
.andExpect(status().isCreated());
// Validate the Gallery in the database
List<Gallery> galleryList = galleryRepository.findAll();
assertThat(galleryList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteGallery() throws Exception {
// Initialize the database
galleryService.save(gallery);
int databaseSizeBeforeDelete = galleryRepository.findAll().size();
// Get the gallery
restGalleryMockMvc.perform(delete("/api/galleries/{id}", gallery.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Gallery> galleryList = galleryRepository.findAll();
assertThat(galleryList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Gallery.class);
}
}
<file_sep>/**
* Spring Framework configuration files.
*/
package org.codingblog.config;
<file_sep>package org.codingblog.web.rest;
import org.codingblog.CodeBlogApp;
import org.codingblog.domain.Comment;
import org.codingblog.repository.CommentRepository;
import org.codingblog.service.CommentService;
import org.codingblog.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.ZoneId;
import java.util.List;
import static org.codingblog.web.rest.TestUtil.sameInstant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the CommentResource REST controller.
*
* @see CommentResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CodeBlogApp.class)
public class CommentResourceIntTest {
private static final Long DEFAULT_ARTICLE_ID = 1L;
private static final Long UPDATED_ARTICLE_ID = 2L;
private static final String DEFAULT_EMAIL = "AAAAAAAAAA";
private static final String UPDATED_EMAIL = "BBBBBBBBBB";
private static final String DEFAULT_CONTENT = "AAAAAAAAAA";
private static final String UPDATED_CONTENT = "BBBBBBBBBB";
private static final ZonedDateTime DEFAULT_CREATE_TIME = ZonedDateTime.ofInstant(Instant.ofEpochMilli(0L), ZoneOffset.UTC);
private static final ZonedDateTime UPDATED_CREATE_TIME = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
private static final Long DEFAULT_PARENT_ID = 1L;
private static final Long UPDATED_PARENT_ID = 2L;
@Autowired
private CommentRepository commentRepository;
@Autowired
private CommentService commentService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restCommentMockMvc;
private Comment comment;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
CommentResource commentResource = new CommentResource(commentService);
this.restCommentMockMvc = MockMvcBuilders.standaloneSetup(commentResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Comment createEntity(EntityManager em) {
Comment comment = new Comment()
.articleId(DEFAULT_ARTICLE_ID)
.email(DEFAULT_EMAIL)
.content(DEFAULT_CONTENT)
.createTime(DEFAULT_CREATE_TIME)
.parentId(DEFAULT_PARENT_ID);
return comment;
}
@Before
public void initTest() {
comment = createEntity(em);
}
@Test
@Transactional
public void createComment() throws Exception {
int databaseSizeBeforeCreate = commentRepository.findAll().size();
// Create the Comment
restCommentMockMvc.perform(post("/api/comments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(comment)))
.andExpect(status().isCreated());
// Validate the Comment in the database
List<Comment> commentList = commentRepository.findAll();
assertThat(commentList).hasSize(databaseSizeBeforeCreate + 1);
Comment testComment = commentList.get(commentList.size() - 1);
assertThat(testComment.getArticleId()).isEqualTo(DEFAULT_ARTICLE_ID);
assertThat(testComment.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(testComment.getContent()).isEqualTo(DEFAULT_CONTENT);
assertThat(testComment.getCreateTime()).isEqualTo(DEFAULT_CREATE_TIME);
assertThat(testComment.getParentId()).isEqualTo(DEFAULT_PARENT_ID);
}
@Test
@Transactional
public void createCommentWithExistingId() throws Exception {
int databaseSizeBeforeCreate = commentRepository.findAll().size();
// Create the Comment with an existing ID
comment.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restCommentMockMvc.perform(post("/api/comments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(comment)))
.andExpect(status().isBadRequest());
// Validate the Alice in the database
List<Comment> commentList = commentRepository.findAll();
assertThat(commentList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllComments() throws Exception {
// Initialize the database
commentRepository.saveAndFlush(comment);
// Get all the commentList
restCommentMockMvc.perform(get("/api/comments?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(comment.getId().intValue())))
.andExpect(jsonPath("$.[*].articleId").value(hasItem(DEFAULT_ARTICLE_ID.intValue())))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL.toString())))
.andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString())))
.andExpect(jsonPath("$.[*].createTime").value(hasItem(sameInstant(DEFAULT_CREATE_TIME))))
.andExpect(jsonPath("$.[*].parentId").value(hasItem(DEFAULT_PARENT_ID.intValue())));
}
@Test
@Transactional
public void getComment() throws Exception {
// Initialize the database
commentRepository.saveAndFlush(comment);
// Get the comment
restCommentMockMvc.perform(get("/api/comments/{id}", comment.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(comment.getId().intValue()))
.andExpect(jsonPath("$.articleId").value(DEFAULT_ARTICLE_ID.intValue()))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL.toString()))
.andExpect(jsonPath("$.content").value(DEFAULT_CONTENT.toString()))
.andExpect(jsonPath("$.createTime").value(sameInstant(DEFAULT_CREATE_TIME)))
.andExpect(jsonPath("$.parentId").value(DEFAULT_PARENT_ID.intValue()));
}
@Test
@Transactional
public void getNonExistingComment() throws Exception {
// Get the comment
restCommentMockMvc.perform(get("/api/comments/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateComment() throws Exception {
// Initialize the database
commentService.save(comment);
int databaseSizeBeforeUpdate = commentRepository.findAll().size();
// Update the comment
Comment updatedComment = commentRepository.findOne(comment.getId());
updatedComment
.articleId(UPDATED_ARTICLE_ID)
.email(UPDATED_EMAIL)
.content(UPDATED_CONTENT)
.createTime(UPDATED_CREATE_TIME)
.parentId(UPDATED_PARENT_ID);
restCommentMockMvc.perform(put("/api/comments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedComment)))
.andExpect(status().isOk());
// Validate the Comment in the database
List<Comment> commentList = commentRepository.findAll();
assertThat(commentList).hasSize(databaseSizeBeforeUpdate);
Comment testComment = commentList.get(commentList.size() - 1);
assertThat(testComment.getArticleId()).isEqualTo(UPDATED_ARTICLE_ID);
assertThat(testComment.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testComment.getContent()).isEqualTo(UPDATED_CONTENT);
assertThat(testComment.getCreateTime()).isEqualTo(UPDATED_CREATE_TIME);
assertThat(testComment.getParentId()).isEqualTo(UPDATED_PARENT_ID);
}
@Test
@Transactional
public void updateNonExistingComment() throws Exception {
int databaseSizeBeforeUpdate = commentRepository.findAll().size();
// Create the Comment
// If the entity doesn't have an ID, it will be created instead of just being updated
restCommentMockMvc.perform(put("/api/comments")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(comment)))
.andExpect(status().isCreated());
// Validate the Comment in the database
List<Comment> commentList = commentRepository.findAll();
assertThat(commentList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteComment() throws Exception {
// Initialize the database
commentService.save(comment);
int databaseSizeBeforeDelete = commentRepository.findAll().size();
// Get the comment
restCommentMockMvc.perform(delete("/api/comments/{id}", comment.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Comment> commentList = commentRepository.findAll();
assertThat(commentList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Comment.class);
}
}
<file_sep>package org.codingblog.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.time.ZonedDateTime;
import java.util.Objects;
/**
* A Gallery.
*/
@Entity
@Table(name = "gallery")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Gallery implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id")
private Long userId;
@Column(name = "label_name")
private String labelName;
@Column(name = "category")
private String category;
@Column(name = "img_url")
private String imgUrl;
@Column(name = "short_msg")
private String shortMsg;
@Column(name = "create_time")
private ZonedDateTime createTime;
@Column(name = "resource_type")
private Integer resourceType;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public Gallery userId(Long userId) {
this.userId = userId;
return this;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getLabelName() {
return labelName;
}
public Gallery labelName(String labelName) {
this.labelName = labelName;
return this;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public String getCategory() {
return category;
}
public Gallery category(String category) {
this.category = category;
return this;
}
public void setCategory(String category) {
this.category = category;
}
public String getImgUrl() {
return imgUrl;
}
public Gallery imgUrl(String imgUrl) {
this.imgUrl = imgUrl;
return this;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getShortMsg() {
return shortMsg;
}
public Gallery shortMsg(String shortMsg) {
this.shortMsg = shortMsg;
return this;
}
public void setShortMsg(String shortMsg) {
this.shortMsg = shortMsg;
}
public ZonedDateTime getCreateTime() {
return createTime;
}
public Gallery createTime(ZonedDateTime createTime) {
this.createTime = createTime;
return this;
}
public void setCreateTime(ZonedDateTime createTime) {
this.createTime = createTime;
}
public Integer getResourceType() {
return resourceType;
}
public Gallery resourceType(Integer resourceType) {
this.resourceType = resourceType;
return this;
}
public void setResourceType(Integer resourceType) {
this.resourceType = resourceType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Gallery gallery = (Gallery) o;
if (gallery.id == null || id == null) {
return false;
}
return Objects.equals(id, gallery.id);
}
@Override
public int hashCode() {
return Objects.hashCode(id);
}
@Override
public String toString() {
return "Gallery{" +
"id=" + id +
", userId='" + userId + "'" +
", labelName='" + labelName + "'" +
", category='" + category + "'" +
", imgUrl='" + imgUrl + "'" +
", shortMsg='" + shortMsg + "'" +
", createTime='" + createTime + "'" +
", resourceType='" + resourceType + "'" +
'}';
}
}
<file_sep>package org.codingblog.repository;
import org.codingblog.domain.Gallery;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the Gallery entity.
*/
@SuppressWarnings("unused")
public interface GalleryRepository extends JpaRepository<Gallery,Long> {
}
| 804ce29d2787d5c3900b5a319ebd183bdd901620 | [
"Java"
] | 6 | Java | haiguangbo/CodeBlog | 977fac5d5dc852a0412f7a262e617eca4e9c1ede | 757af1057a2b3be022e1db78014014e3fde40528 | |
refs/heads/master | <repo_name>SebTuc/GoTicTacToe<file_sep>/go.mod
module github.com/SebTuc/TicTacToe
go 1.13<file_sep>/main.go
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
type tictactoeboard [3][3]rune
const (
playerShape = 'O'
computerShape = 'X'
)
func main() {
var whoWon string
var win bool
var retry bool
var board tictactoeboard
retry = true
for retry {
board.clear()
for i := 0; i < 9; i++ {
board.displayBoard()
if i%2 == 0 {
board.player()
} else {
board.computer()
}
_, win = board.check()
if win {
break
}
}
whoWon, win = board.check()
if win {
fmt.Printf("--------- %v won ---------\nFinal board:\n", whoWon)
} else {
fmt.Println("--------- draw ---------\nFinal board:")
}
board.displayBoard()
retry = wantRetry()
}
}
func wantRetry() bool {
var valuePlay string
fmt.Println("do you want retry this game ?(Y/N)")
if _, err := fmt.Scan(&valuePlay); err == nil {
if strings.ToUpper(valuePlay) == "Y" {
return true
} else if strings.ToUpper(valuePlay) == "N" {
return false
} else {
fmt.Println("error input")
wantRetry()
}
} else {
fmt.Println("error input")
wantRetry()
}
return false
}
func (t *tictactoeboard) displayBoard() {
fmt.Print("-------------")
for i := 0; i < 3; i++ {
fmt.Print("\n|")
for j := 0; j < 3; j++ {
fmt.Printf(" %c |", t[i][j])
}
fmt.Print("\n------------")
}
fmt.Println()
}
func (t *tictactoeboard) clear() {
for x, v := range t {
for y := range v {
t[x][y] = 0
}
}
}
func (t *tictactoeboard) player() {
//set value of user play and check if is correct and not printed
var column int32
var line int32
for {
fmt.Println("Choose Row and column (between 1 and 3):")
if _, err := fmt.Scan(&line, &column); err == nil {
line--
column--
if line >= 0 && line <= 3 && column >= 0 && column <= 3 && t[line][column] == 0 {
t[line][column] = playerShape
break
} else {
if line >= 0 && line <= 3 && column >= 0 && column <= 3 {
fmt.Printf("You input value is already use on line %v and column %v , value => %v\n", line+1, column+1, string(t[line][column]))
} else {
fmt.Printf("You input value is not corrected, line : %v , column : %v \n", line+1, column+1)
}
}
} else {
fmt.Println("Your input value is not correct")
t.player()
}
}
}
func (t *tictactoeboard) computer() {
// random value set for
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
for {
line := r1.Intn(3)
column := r1.Intn(3)
if line >= 0 && line <= 3 && column >= 0 && column <= 3 && t[line][column] == 0 {
t[line][column] = computerShape
break
}
}
}
func (t *tictactoeboard) check() (string, bool) {
//check if as a winner
for x, v := range t {
for y := range v {
if t.checkArround(x, y) {
if t[x][y] == playerShape {
return "Player", true
} else {
return "Computer", true
}
}
}
}
return "", false
}
func (t *tictactoeboard) checkArround(x, y int) bool {
test := true
symbole := t[x][y]
if symbole == 0 {
return false
}
for line := 0; line < 3; line++ {
if t[line][y] != symbole {
test = false
break
}
}
if !test {
test = true
for column := 0; column < 3; column++ {
if t[x][column] != symbole {
test = false
break
}
}
if !test {
test = true
if x == 1 && y == 1 {
if t[0][0] != symbole || t[2][2] != symbole {
test = false
} else {
test = true
}
if !test || (t[0][2] != symbole || t[2][0] != symbole) {
test = false
}
} else if x == 0 && y == 0 {
if t[1][1] != symbole || t[2][2] != symbole {
test = false
}
} else if x == 0 && y == 2 {
if t[1][1] != symbole || t[2][0] != symbole {
test = false
}
} else if x == 2 && y == 0 {
if t[1][1] != symbole || t[0][2] != symbole {
test = false
}
} else if x == 2 && y == 2 {
if t[1][1] != symbole || t[0][0] != symbole {
test = false
}
} else {
test = false
}
}
}
return test
}
| b59c438c789d035c80363a56f86ccf8ebf56beba | [
"Go",
"Go Module"
] | 2 | Go Module | SebTuc/GoTicTacToe | ecc93c6012a485e0218f3038b55ea6b350035018 | a4873ec361ace3ae7d597e93dfe534401ebdcd55 | |
refs/heads/master | <file_sep>import React from 'react';
class Weather extends React.Component {
render() {
return(
<div className="widget-17 panel no-border no-margin widget-loader-circle">
<div className="panel-heading">
<div className="panel-title">
<i className="pg-map"></i> California, USA
<span className="caret"></span>
</div>
<div className="panel-controls">
<ul>
<li className="">
<div className="dropdown">
<a data-target="#" href="#" data-toggle="dropdown" aria-haspopup="true" role="button" aria-expanded="false">
<i className="portlet-icon portlet-icon-settings"></i>
</a>
<ul className="dropdown-menu pull-right" role="menu">
<li><a href="#">AAPL</a>
</li>
<li><a href="#">YHOO</a>
</li>
<li><a href="#">GOOG</a>
</li>
</ul>
</div>
</li>
<li>
<a data-toggle="refresh" className="portlet-refresh text-black" href="#"><i
className="portlet-icon portlet-icon-refresh"></i></a>
</li>
</ul>
</div>
</div>
<div className="panel-body">
<div className="p-l-5">
<div className="row">
<div className="col-md-12 col-xlg-6">
<div className="row m-t-20">
<div className="col-md-5">
<h4 className="no-margin">Monday</h4>
<p className="small hint-text">9th August 2014</p>
</div>
<div className="col-md-7">
<div className="pull-left">
<p className="small hint-text no-margin">Currently</p>
<h4 className="text-danger bold no-margin">32°
<span className="small">/ 30C</span>
</h4>
</div>
<div className="pull-right">
<canvas height="64" width="64" className="clear-day"></canvas>
</div>
</div>
</div>
<h5>Feels like
<span className="semi-bold">rainy</span>
</h5>
<p>Weather information</p>
<div className="widget-17-weather">
<div className="row">
<div className="col-xs-6 p-r-10">
<div className="row">
<div className="col-md-12">
<p className="pull-left">Wind</p>
<p className="pull-right bold">11km/h</p>
</div>
</div>
<div className="row">
<div className="col-md-12">
<p className="pull-left">Sunrise</p>
<p className="pull-right bold">05:20</p>
</div>
</div>
<div className="row">
<div className="col-md-12">
<p className="pull-left">Humidity</p>
<p className="pull-right bold">20%</p>
</div>
</div>
<div className="row">
<div className="col-md-12">
<p className="pull-left">Precipitation</p>
<p className="pull-right bold">60%</p>
</div>
</div>
</div>
<div className="col-xs-6 p-l-10">
<div className="row">
<div className="col-md-12">
<p className="pull-left">Sunset</p>
<p className="pull-right bold">21:05</p>
</div>
</div>
<div className="row">
<div className="col-md-12">
<p className="pull-left">Visibility</p>
<p className="pull-right bold">21km</p>
</div>
</div>
</div>
</div>
</div>
<div className="row m-t-10 timeslot">
<div className="col-xs-2 p-t-10 text-center">
<p className="small">13:30</p>
<canvas height="25" width="25" className="partly-cloudy-day"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-xs-2 p-t-10 text-center">
<p className="small">14:00</p>
<canvas height="25" width="25" className="cloudy"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-xs-2 p-t-10 text-center">
<p className="small">14:30</p>
<canvas height="25" width="25" className="rain"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-xs-2 p-t-10 text-center">
<p className="small">15:00</p>
<canvas height="25" width="25" className="sleet"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-xs-2 p-t-10 text-center">
<p className="small">15:30</p>
<canvas height="25" width="25" className="snow"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-xs-2 p-t-10 text-center">
<p className="small">16:00</p>
<canvas height="25" width="25" className="wind"></canvas>
<p className="text-danger bold">30°C</p>
</div>
</div>
</div>
<div className="col-xlg-6 visible-xlg">
<div className="row">
<div className="forecast-day col-md-6 text-center m-t-10 ">
<div className="bg-master-lighter p-b-10 p-t-10">
<h4 className="p-t-10 no-margin">Tuesday</h4>
<p className="small hint-text m-b-20">11th Augest 2014</p>
<canvas className="rain" width="64" height="64"></canvas>
<h5 className="text-danger">32°</h5>
<p>Feels like
<span className="bold">sunny</span>
</p>
<p className="small">Wind
<span className="bold p-l-20">11km/h</span>
</p>
<div className="m-t-20 block">
<div className="padding-10">
<div className="row">
<div className="col-md-6 text-center">
<p className="small">Noon</p>
<canvas className="sleet" width="25" height="25"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-md-6 text-center">
<p className="small">Night</p>
<canvas className="wind" width="25" height="25"></canvas>
<p className="text-danger bold">30°C</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="col-md-6 text-center m-t-10 ">
<div className="bg-master-lighter p-b-10 p-t-10">
<h4 className="p-t-10 no-margin">Wednesday</h4>
<p className="small hint-text m-b-20">11th Augest 2014</p>
<canvas className="rain" width="64" height="64"></canvas>
<h5 className="text-danger">32°</h5>
<p>Feels like
<span className="bold">sunny</span>
</p>
<p className="small">Wind
<span className="bold p-l-20">11km/h</span>
</p>
<div className="m-t-20 block">
<div className="padding-10">
<div className="row">
<div className="col-md-6 text-center">
<p className="small">Noon</p>
<canvas className="sleet" width="25" height="25"></canvas>
<p className="text-danger bold">30°C</p>
</div>
<div className="col-md-6 text-center">
<p className="small">Night</p>
<canvas className="wind" width="25" height="25"></canvas>
<p className="text-danger bold">30°C</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Weather
<file_sep>import React from 'react';
import Counter from './dashboard/Counter';
import Other from './dashboard/Other';
class Dashboard extends React.Component {
render() {
return(
<div>
<Counter />
<Other />
</div>
)
}
}
export default Dashboard
<file_sep>import React from 'react';
class HeaderSecond extends React.Component {
render() {
return(
<div className="header ">
<div className=" pull-left sm-table hidden-xs hidden-sm">
<i className="fa fa-list" id="menu-awesome" aria-hidden="true"></i>
</div>
<div className=" pull-left sm-table hidden-xs hidden-sm">
<h3><b>This page is for the owner only</b></h3>
</div>
<div className="pull-right">
<i className="fa fa-user" id="user-awesome" aria-hidden="true"></i>
</div>
</div>
)
}
}
export default HeaderSecond
<file_sep>import React from 'react';
import { Router,browserHistory,Route,IndexRoute } from 'react-router';
import Main from '../components/Main';
import Login from '../components/Login';
import Home from '../components/Home';
import Register from '../components/Register';
import CreateAccount from '../components/container/CreateAccount';
export default (
<Router history={browserHistory}>
<Route path="/" component={Main}>
<Route path="home/:username" component={Home}></Route>
<Route path="newacc" component={CreateAccount}></Route>
<IndexRoute component={Login}/>
</Route>
</Router>
);
<file_sep>import React from 'react';
class Other extends React.Component {
render() {
return(
<div>
<div className="white-box text-center col-md-4">
<h3><b>Orders completed</b></h3>
<br></br>
<p>This is the amount of order you serve since the begining of the time, come on keep it up!! and make your self the best cafe your customer ever dream of. </p>
</div>
<div className="white-box text-center col-md-4">
<h3><b>Unsatisfied Customer</b></h3>
<br></br>
<p>Dont you guys dare to make this zero number above increasing even to one number, all customer are special, all customer are the king. respect them, give em a big smile and say "WELCOME TO ARTHENTIC CAFE HOW CAN I HELP YOU ?"</p>
</div>
<div className="white-box text-center col-md-4">
<h3><b>Who made this app?</b></h3>
<br></br>
<p>it is one and only software house who has a lot of potential and skill with their finger, brain, a cup of coffee and a lil bit smile on their faces and voila! amazing apps is comming to your way
visit: http://www.radiontech.net</p>
</div>
</div>
)
}
}
export default Other
<file_sep>import React from 'react';
import {Link} from 'react-router';
class Login extends React.Component {
handleLogin(val) {
val.preventDefault();
const username = this.usernameRef.value;
const password = this.passwordRef.value;
this.usernameRef.value = '';
this.passwordRef.value = '';
this.context.router.push(`home/${username}`);
}
render() {
return(
<div>
<div className="col-md-4"></div>
<div className="col-md-4">
<div className="login-container login bg-white">
<div className="p-l-50 m-l-20 p-r-50 m-r-20 p-t-50 m-t-30 sm-p-l-15 sm-p-r-15 sm-p-t-40">
{/*<img src="assets/img/logo.png" alt="logo" data-src="assets/img/logo.png" data-src-retina="assets/img/logo_2x.png" width="78" height="22"/>*/}
<h1 className="text-center"><b>Radical Technology</b></h1>
<p className="p-t-35">Welcome back, this is Radical Technology System!</p>
<form id="form-login" className="p-t-15" role="form">
<div className="form-group form-group-default">
<label>Login</label>
<div className="controls">
<input type="text" name="username" placeholder="User Name" className="form-control" ref={(ref) => this.usernameRef = ref} required/>
</div>
</div>
<div className="form-group form-group-default">
<label>Password</label>
<div className="controls">
<input type="<PASSWORD>" className="form-control" name="password" placeholder="<PASSWORD>" ref={(ref) => this.passwordRef = ref} required/>
</div>
</div>
<div className="row">
</div>
<div className="">
<p>
New user? <Link to={'newacc'}>create new account here</Link>
</p>
</div>
<button onClick={(val) => this.handleLogin(val)} className="btn btn-primary btn-cons m-t-10 log_in" type="submit">Sign in</button>
</form>
<br></br>
<br></br>
<br></br>
<br></br>
<br></br>
<div className="text-right">
<img className="logo-login" src="assets/img/kirim.jpg"/>
</div>
</div>
</div>
</div>
<div className="col-md-4"> </div>
</div>
)
}
}
Login.contextTypes = {
router: React.PropTypes.object.isRequired
}
export default Login
<file_sep>import React from 'react';
import {Link} from 'react-router';
class Header extends React.Component {
render() {
return(
<div className="header ">
<div className=" pull-left sm-table hidden-xs hidden-sm">
<i className="fa fa-list" id="menu-awesome" aria-hidden="true"></i>
</div>
<div className=" pull-left sm-table hidden-xs hidden-sm">
<h3><b>Radion Dashboard</b></h3>
</div>
<div className="pull-right">
<span id="hi-panel">hi, Nancy</span>
<Link to="/"><i className="fa fa-sign-out" id="sign-out-awesome" aria-hidden="true"></i></Link>
<i className="fa fa-cog" id="cog-awesome" aria-hidden="true"></i>
<i className="fa fa-user" id="user-awesome" aria-hidden="true"></i>
</div>
</div>
)
}
}
export default Header
| 609b71cd903362f2e0d5de1b479a87b7161dc19c | [
"JavaScript"
] | 7 | JavaScript | valentinancy/arthentic | 513f6e178ea6f6ddfed045e8ff3e9056d5e94034 | 6ccdf59e8a645b23a932a3f9195eb21e0551b5fa | |
refs/heads/master | <file_sep>/**
* Created by jeanzhao on 10/23/18.
*/
export const DefaultConfig = {
// puppeteer launch setting
launchOptions: {
headless: false,
defaultViewport: {
width: 1024,
height: 768
},
timeout: 60 * 60 * 1000
},
// delay for visiting a link
indexPageDelay: 5000,
linkDelay: 2000,
clickDelay: 1000,
// force to initialize opening chrome
init: true
};
<file_sep>/**
* Created by jeanzhao on 10/23/18.
*/
export * from "./macrodownload";
<file_sep>import { Subject } from "rxjs";
declare interface LaunchOptions {
/**
* Whether to open chrome in appMode.
* @default false
*/
appMode?: boolean;
/**
* Whether to ignore HTTPS errors during navigation.
* @default false
*/
ignoreHTTPSErrors?: boolean;
/**
* Do not use `puppeteer.defaultArgs()` for launching Chromium.
* @default false
*/
ignoreDefaultArgs?: boolean | string[];
/**
* Whether to run Chromium in headless mode.
* @default true
*/
headless?: boolean;
/**
* Path to a Chromium executable to run instead of bundled Chromium. If
* executablePath is a relative path, then it is resolved relative to current
* working directory.
*/
executablePath?: string;
/**
* Slows down Puppeteer operations by the specified amount of milliseconds.
* Useful so that you can see what is going on.
*/
slowMo?: number;
/**
* Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport.
*/
defaultViewport?: {
/**
* page width in pixels.
*/
width?: number;
/**
* page height in pixels.
*/
height?: number;
/**
* Specify device scale factor (can be thought of as dpr).
* @default 1
*/
deviceScaleFactor?: number;
/**
* Whether the meta viewport tag is taken into account.
* @default false
*/
isMobile?: boolean;
/**
*
* Specifies if viewport supports touch events.
* @default false
*/
hasTouch?: boolean;
/**
* Specifies if viewport is in landscape mode.
* @default false
*/
isLandscape?: boolean;
};
/**
* Additional arguments to pass to the Chromium instance. List of Chromium
* flags can be found here.
*/
args?: string[];
/**
* Close chrome process on Ctrl-C.
* @default true
*/
handleSIGINT?: boolean;
/**
* Close chrome process on SIGTERM.
* @default true
*/
handleSIGTERM?: boolean;
/**
* Close chrome process on SIGHUP.
* @default true
*/
handleSIGHUP?: boolean;
/**
* Maximum time in milliseconds to wait for the Chrome instance to start.
* Pass 0 to disable timeout.
* @default 30000 (30 seconds).
*/
timeout?: number;
/**
* Whether to pipe browser process stdout and stderr into process.stdout and
* process.stderr.
* @default false
*/
dumpio?: boolean;
/** Path to a User Data Directory. */
userDataDir?: string;
/**
* Specify environment variables that will be visible to Chromium.
* @default `process.env`.
*/
env?: {
[key: string]: string | boolean | number;
};
/**
* Whether to auto-open DevTools panel for each tab. If this option is true, the headless option will be set false.
*/
devtools?: boolean;
/**
* Connects to the browser over a pipe instead of a WebSocket.
* @default false
*/
pipe?: boolean;
}
declare interface linkInfo {
/**
* description for this download link:
* could be set as widget name, action description
*/
name: string;
/**
* selector for download body:
* would click download link until the body is ready
*/
waitSelector: string;
/**
* selector for possible error
* could save much time instead of timeout for waitSelector
*/
errorSelector: string;
/**
* selector for download link
*/
downloadLink: string;
}
declare interface ERROR {
type: string;
info: string;
}
export interface Options {
/**
* site to visit
*/
site: string;
/**
* launch options for using puppeteer
* @default read from defaultConfig.ts file
*/
launchOptions?: LaunchOptions;
/**
* whether to force to initialize opening chrome
* @default read from defaultConfig.ts file
* */
init?: boolean;
/**
* delay in milliseconds to wait for the Chrome instance to start.
* @default read from defaultConfig.ts file
*/
indexPageDelay?: number;
/**
* delay in milliseconds to wait for the possible rendering time of link
* @default read from defaultConfig.ts file
*/
linkDelay?: number;
/**
* delay in milliseconds to wait for the possible responding time of link
* @default read from defaultConfig.ts file
*/
clickDelay?: number;
}
export interface Task {
/**
* task name:
* special one for same macroId
*/
name: string;
/**
* basis for calculating progress
*/
macroId: string;
/**
* menu selector list for sequentially click
*/
menuList?: string[];
/**
* directory path for multiple download files
*/
downloadPath: string;
/**
* a list of download link information for this menu link
*/
downloadLink: linkInfo[];
/**
* option value set in widgets after clicking current menu link
*/
param?: any;
}
export interface TaskStatus {
/**
* task name:
* special one for same macroId
*/
name: string;
/**
* process info for the browser
*/
processInfo: ProcessInfo;
/**
* basis for calculating progress
*/
macroId: string;
/**
* total number for downloading links
*/
total: number;
/**
* successful number for downloading links
*/
success: number;
/**
* a list of error info during downloading files
*/
errInfo: ERROR[];
/**
* other reported error case:
* e.g. the browser is closed manually.
*/
otherErr: ERROR[];
}
export interface ProcessInfo {
pid: number;
cpu: number;
}
export declare class MacroDownload {
runningSteam: Subject<TaskStatus[]>;
constructor();
static getCustomizedOptions(options: Options): Options;
download(tasks: Task[], options: Options): Promise<void>;
close(): Promise<void>;
getCpuProcess(processId?: number): Promise<ProcessInfo>;
getRunningProcess(): any;
}
<file_sep>/**
* Created by jeanzhao on 10/23/18.
*/
export * from "./job/MacroDownload";<file_sep>/**
* Created by jeanzhao on 11/23/18.
*/
import {LaunchOptions} from "../model/Options";
import * as winston from "winston";
export class UtilService {
private static _instance: UtilService = new UtilService();
constructor(){
UtilService._instance = this;
}
static isNull(i: any): boolean {
return Object.prototype.toString.call(i) === "[object Null]";
}
static isUndefined(i: any): boolean {
return Object.prototype.toString.call(i) === "[object Undefined]";
}
static isString(i: any): boolean {
return Object.prototype.toString.call(i) === "[object String]";
}
static isEqualValue(p1: LaunchOptions, p2: LaunchOptions): boolean {
let result;
for (let k in p1) {
result = p1[k] !== p2[k];
}
return result;
}
delay(time: number): Promise<string> {
return new Promise(resolve => {
setTimeout(() => resolve(""), time);
});
}
mapSeries(array: any[], promise: (value, index) => Promise<any>): Promise<any> {
if (array.length > 0) {
return array.reduce((p, c, i) => p.then(() => promise(c, i)), Promise.resolve());
} else {
winston.info(`found empty list need execution.`);
return Promise.resolve();
}
}
}<file_sep>/**
* Created by jeanzhao on 11/23/18.
*/
export interface TaskStatus {
/**
* task name:
* special one for same macroId
*/
name: string;
/**
* process info for the browser
*/
processInfo: ProcessInfo;
/**
* basis for calculating progress
*/
macroId: string;
/**
* total number for downloading links
*/
total: number;
/**
* successful number for downloading links
*/
success: number;
/**
* a list of error info during downloading files
*/
errInfo: ERROR[];
/**
* other reported error case:
* e.g. the browser is closed manually.
*/
otherErr: ERROR[];
}
export interface ERROR {
type: string,
info: string
}
export interface ProcessInfo {
pid: number,
cpu: number
}<file_sep># macro-execution
This is a simple plug-in based on puppeteer.
Currently it supports macro download. It helps monitoring tasks status for macro downloading files from a virtual web page.
It also provides customized settings and pushes download progress for per task.
Please feel free to use it in javascript or typescript projects.
## Install
* npm install macro-execution
## Usage
### Used in js projects:
```js
let me = require(`macro-execution`);
function A(tasks){
let test = new me.MacroDownload();
return test.download(tasks, {site: 'localhost:3000'})
.then(test.close);
}
let tasks = [{
name: '<NAME>', // task name
menuList: [], // nested menu wait to be clicked
downloadPath: './Test', // the directory to download files
downloadLink: [], // download link set, e.g.
// linkInfo {
// name: ''
// waitSelector: '' // selector for download body
// errorSelector: '' // selector for possible error
// downloadLink: '' // selector for download link
// }
macroId: 'q1' // unique id for running tasks
}];
A(tasks);
```
### Used in ts projects:
```ts
import {Task, MacroDownload} from 'macro-execution';
export function A(tasks: Task[]): Promise<void> {
let test = new MacroDownload();
return test.download(tasks, {site: 'http://localhost:3000'})
.then(test.close);
}
```
## Launch options
| Parameters | default Value | Descriptions
| --- | --- | --- |
| `site` | `--` | `must be set: site to visit`
## API
* Disconnect
```js
test.close();
```
* Monitoring task status
```js
test.runningSteam.subscribe(list => {
// do something with ${list}
// [{ "name":"<NAME>",
// "processInfo": {"pid":25459,"cpu":0}, // process id and cpu info
// "macroId":"q1", // unique id for running tasks
// "total":0, // total number for per task
// "success":0, // current success number for per task
// "errInfo":[], // error message
// "otherErr":[] // unexpected error message collection
// }]
});
```
# Coming soon
More supports is coming...
It's for open source learning.
Any questions please feel free to contact me.
<file_sep>/**
* Created by jeanzhao on 10/23/18.
*/
export interface Task {
/**
* task name:
* special one for same macroId
*/
name: string;
/**
* basis for calculating progress
*/
macroId: string;
/**
* menu selector list for sequentially click
*/
menuList?: string[];
/**
* directory path for multiple download files
*/
downloadPath: string;
/**
* a list of download link information for this menu link
*/
downloadLink: linkInfo[];
/**
* option value set in widgets after clicking current menu link
*/
param?: any;
}
export interface linkInfo {
/**
* description for this download link:
* could be set as widget name, action description
*/
name: string;
/**
* selector for download body:
* would click download link until the body is ready
*/
waitSelector: string;
/**
* selector for possible error
* could save much time instead of timeout for waitSelector
*/
errorSelector: string;
/**
* selector for download link
*/
downloadLink: string;
}<file_sep>/**
* Created by jeanzhao on 12/23/18.
*/
import * as puppeteer from "puppeteer";
import {UtilService} from "../Services/utils";
import {Subject} from "rxjs";
import {Options, LaunchOptions} from "../model/Options";
import {DefaultConfig} from "../model/defaultConfig";
import {Task} from "../model/Task";
import {ERROR, ProcessInfo, TaskStatus} from "../model/TaskStatus";
import * as winston from "winston";
import * as pidUsage from 'pidusage';
export class MacroDownload {
private utils = new UtilService();
private browser: any;
private launch: LaunchOptions;
private runningList: TaskStatus[] = [];
public runningSteam: Subject<TaskStatus[]> = new Subject<TaskStatus[]>();
constructor() {
}
static getCustomizedOptions(options: Options): Options {
let result: any = Object.assign({}, DefaultConfig);
if (options.launchOptions) {
Object.assign(result.launchOptions, options.launchOptions);
}
let remainingConf = Object.assign({}, options);
for (let attr in remainingConf) {
if (attr === 'launchOptions') delete remainingConf[attr];
}
Object.assign(result, remainingConf);
return result;
}
public async close() {
await this.utils.delay(DefaultConfig.indexPageDelay);
await this.browser.close();
await pidUsage.clear();
this.browser = null;
this.launch = null;
this.runningSteam = null;
return;
}
public async getCpuProcess(processId?: number): Promise<ProcessInfo> {
let pid = processId || this.getRunningProcess().pid;
let cpu = 0;
if (pid) {
let stat = await pidUsage(pid);
cpu = stat.cpu ? +(stat.cpu).toFixed(2) : 0;
}
return {pid, cpu};
}
public getRunningProcess() {
return this.browser ? this.browser.process() : {};
}
public async initTaskList(tasks: Task[]) {
const processInfo = await this.getCpuProcess();
tasks.forEach(task => {
const index = this.runningList.findIndex(t => t.name === task.name && t.macroId === task.macroId);
if (index !== -1) {
this.runningList[index].total = +this.runningList[index].total + task.downloadLink.filter(i => !!i.downloadLink).length;
} else {
this.runningList.push({
"name": task.name,
"processInfo": processInfo,
"macroId": task.macroId,
"total": task.downloadLink.filter(i => !!i.downloadLink).length,
"success": 0,
"errInfo": [],
"otherErr": []
});
}
});
this.runningSteam.next(this.runningList);
return;
}
public async download(tasks: Task[], options: Options) {
let page = await this.openWebPage(options,
() => this.initTaskList(tasks)
);
winston.info(`start macro download, task numbers:${tasks.length}`);
await this.utils.mapSeries(tasks, async task => {
try {
await (page as any)._client.send('Page.setDownloadBehavior', {
behavior: 'allow',
downloadPath: task.downloadPath
});
let successIndex = 0;
const total = task.downloadLink.filter(i => !!i.downloadLink).length;
// 1. click nested menu
await this.utils.mapSeries(task.menuList, async (menuSelector, index) => {
winston.info(`click menu with selector:${menuSelector}`);
await this.clickBySelector(menuSelector, task, page);
});
// 2. download files after the last menu link
await this.utils.mapSeries(task.downloadLink, async linkInfo => {
winston.info(`start to download a file for ${linkInfo.name}`);
try {
await this.raceCheck(linkInfo.waitSelector, linkInfo.errorSelector, page);
let downloadContent = await this.raceCheck(linkInfo.downloadLink, linkInfo.errorSelector, page);
await this.clickHandler(downloadContent);
successIndex++;
this.pushList({task: task, success: 1});
winston.debug(`Complete ${successIndex}/${total} for downloading ${task.name}${task.param ? ' with param ' + JSON.stringify(task.param) : ''}`);
await this.utils.delay(DefaultConfig.clickDelay);
} catch (e) {
const info = `fail download file for ${linkInfo.name} of link '${task.name}'${task.param ? ' with param ' + JSON.stringify(task.param) : ''}`;
this.errHandler(task, e.message ? e : info);
}
});
} catch (e) {
this.errHandler(task, e);
}
});
return;
}
private async openWebPage(options: Options, launchCallback?: () => void) {
let conf = MacroDownload.getCustomizedOptions(options);
if (this.isNeedLaunch(conf)) {
this.launch = conf.launchOptions;
this.browser = await puppeteer.launch(this.launch);
if (launchCallback) {
launchCallback();
}
}
let page = await this.browser.newPage();
await page.goto(`${conf.site}`);
await this.utils.delay(conf.indexPageDelay);
return page;
}
private isNeedLaunch(options: Options): boolean {
return UtilService.isNull(this.browser) || UtilService.isUndefined(this.browser)
|| (options.init && this.launch
&& !UtilService.isEqualValue(this.launch, options.launchOptions));
}
private async pushList(item: { task: Task, success?: number, err?: ERROR }) {
const index = this.runningList.findIndex(t => t.name === item.task.name && t.macroId === item.task.macroId);
if (index !== -1) {
let curLink = this.runningList[index];
if (item.success) {
curLink["success"] = +curLink["success"] + item.success;
}
if (item.err) {
const errKey = item.err.type === "download" ? "err" : "otherErr";
item.err.info = `[${curLink.macroId}]: ${item.err.info}`;
if (!errKey.includes(item.err.info)) {
curLink[errKey].push(item.err.info);
}
}
curLink.processInfo = await this.getCpuProcess(curLink.processInfo.pid);
this.runningSteam.next(this.runningList);
}
}
private async clickBySelector(selector: string, task: Task, page: any) {
try {
let curMenu = await page.waitForSelector(selector, {timeout: this.launch.timeout});
await this.clickHandler(curMenu);
return;
} catch (e) {
this.errHandler(task, e);
}
}
private raceCheck(selector: string, errorSelector: string, page: any): Promise<any> {
return Promise.race([this.checkSelector(selector, page), this.checkSelector(errorSelector, page)]);
}
private checkSelector(selector: string, page: any): Promise<any> {
return page.waitForSelector(selector, {timeout: this.launch.timeout})
.then(value => {
return selector.includes('img[src$=\'/error_500.png\']') ? Promise.reject() : Promise.resolve(value);
});
}
private async clickHandler($selector: any) {
await $selector.click({clickCount: 1, delay: DefaultConfig.clickDelay});
await this.utils.delay(DefaultConfig.clickDelay);
return;
}
private errHandler(task: Task, e: any) {
let err;
if (UtilService.isString(e)) {
err = {"type": "download", "info": e};
} else {
err = {"type": "other", "info": e.message || JSON.stringify(e)};
}
this.pushList({task: task, err: err});
return;
}
}
| 1ae12e6bfafcd19caadb8eb85f3610a3f6806eb9 | [
"Markdown",
"TypeScript"
] | 9 | TypeScript | JeanZhao/macrodownload | c0997846a119483b3346627b060813c6334a8f8c | 08c21d35b15c9b92343dac5bf35ebcf1f1d4bf21 | |
refs/heads/master | <file_sep>JavaWebScoket
=============
<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.
*/
package com.apuntesdejava.websocket;
import javax.websocket.server.ServerEndpointConfig;
/**
*
* @author LuzMary
*/
public class WebSocketConfig extends ServerEndpointConfig.Configurator {
//private static BroadcastUsuariosEndPoint websocketconf = new BroadcastUsuariosEndPoint();
@Override
public <T> T getEndpointInstance(Class <T> endpointClass) throws InstantiationException
{
if (BroadcastUsuariosEndPoint.class.equals(endpointClass)) {
return (T)new BroadcastUsuariosEndPoint();
}else
{
throw new InstantiationException();
}
}
}
| 287c0d735db86e3daa4a02a23365a3f793ea2996 | [
"Markdown",
"Java"
] | 2 | Markdown | afcely/JavaWebSockets | 72f1cd36d4d72ca9153dd5990a01c7a4e5678f0a | be1e17aa4d916a789be05a04c21882493d7882c3 | |
refs/heads/master | <repo_name>Naomie-Sebag/web_react_project<file_sep>/backend/models/PackagesModels.js
const mongoose = require('mongoose')
const package = new mongoose.Schema({
distribution_date: {
type:Date,
default: Date.now
},
receiver_name: {
type:String,
required: true
},
latitude: {
type:Number,
required: true
},
longitude: {
type:Number,
required: true
},
address: {
type:String,
required: true
},
IsDistributed: {
type:String,
default:false
},
AssignedTo: {
type:String,
default: ""
}
})
module.exports = mongoose.model('packages', package)<file_sep>/backend/clustering.js
const Pack =require('./models/PackagesModels')
const User =require('./models/SignUpModels')
var clusters = {
groupOrders : function(req,res_of_func) {
Pack.find({}, async (err, result) => {
if (err) throw err;
console.log(result);
var size = JSON.stringify(req.body.KSize);
let vectors = new Array();
for (let i = 0 ; i < result.length ; i++) {
vectors[i] = [ result[i]['longitude'] , result[i]['latitude']];
}
console.log(vectors);
const kmeans = require('node-kmeans');
var size_int = parseInt(size);
kmeans.clusterize(vectors, {k: parseInt(size[1])}, (err,result) => {
if (err)
return res_of_func.status(400).json({'status' : 'Error'});
else {
var str_result = JSON.stringify(result);
console.log("clusterization succeeded: " + str_result)
for(let i=0; i< result.length; i++) {
var str_result_long = JSON.stringify(result[i].cluster[0][0])
var str_result_lat = JSON.stringify(result[i].cluster[0][1])
Pack.findOne({longitude: str_result_long, latitude : str_result_lat}, async (err, res) => {
if (err) throw err;
console.log("package with the Address centroid found: " + res);
User.findOne({city: res.address, isManager : false}, async (err, user_res) => {
if (err) throw err;
console.log("the username is: " + user_res.username);
var new_assignee = {$set : {AssignedTo: user_res.username}};
var str_result_clusterInd = JSON.stringify(result[i].clusterInd);
console.log("cluster index is: " + str_result_clusterInd)
var str_result_clusterInd_length = ((str_result_clusterInd.length/2) - 2);
if((str_result_clusterInd_length % 10) !== 0)
str_result_clusterInd_length += 1.5;
else
str_result_clusterInd_length += 1;
console.log("cluster index length is: " + str_result_clusterInd_length)
for(let j=0; j < str_result_clusterInd_length; j++)
{
// console.log(JSON.stringify(result[j].cluster))
var str_result_long_j = JSON.stringify(result[i].cluster[j][0])
var str_result_lat_j = JSON.stringify(result[i].cluster[j][1])
Pack.updateOne({longitude: str_result_long_j, latitude: str_result_lat_j}, new_assignee, async (err, update_res) => {
if (err) throw err;//"already assigned to someone! wait for delivery or update the distributor";
console.log("update success: " + update_res)
})
}
} )
})
}
return res_of_func.status(200).json("clusterization successful ");
}
});
})
}
}
module.exports = clusters;<file_sep>/backend/Router.js
const express = require('express')
const router = express.Router()
const User =require('./models/SignUpModels')
const Pack =require('./models/PackagesModels')
const bcrypt = require("bcryptjs")
const passport = require("passport");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const session = require("express-session");
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
cors({
origin: "http://localhost:3000", // <-- location of the react app were connecting to
credentials: true,
})
);
app.use(
session({
secret: "secretcode",
resave: true,
saveUninitialized: true,
})
);
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport);
//end of middleware
router.post('/signup', (request, response) => {
User.findOne({ username: request.body.username }, async (err, doc) => {
if (err) throw err;
if (doc) response.send("User Already Exists");
if (!doc) {
const hashedPassword = await bcrypt.hash(request.body.password, 10);
const signedUpUser = new User({
fullName:request.body.fullName,
username:request.body.username,
email:request.body.email,
password:<PASSWORD>,
isManager:request.body.isManager,
city:request.body.city
});
signedUpUser.save()
.then(data =>{
response.json(data)
})
.catch(error =>{
response.json(error)
})
}
});
});
router.post("/login", (request, response) => {
User.findOne({ username: request.body.username }, async (err, doc) => {
if (err) throw err;
if (doc) {
// console.log((doc));
response.json({
authentication: {
"username": doc.username,
"fullName": doc.fullName,
"isManager": doc.isManager
},
message: "User Authentication success"
})
}
if (!doc) {
const hashedPassword = await bcrypt.hash(request.body.password, 10);
response.send("User doesn't exist");
}
})
});
router.post("/showPacks", (request, response) => {
User.findOne({ username: request.body.user_ }, async (err, doc) => {
if (err) throw err;
if (doc) {
Pack.find({AssignedTo: request.body.user_}, async (err, result) => {
if (err) throw err;
console.log(result);
response.send(result)
})
}
});
})
router.post("/createPack", (req, res) => {
const CreatePackage = new Pack({
receiver_name:req.body.receiver_name,
latitude:req.body.latitude,
longitude:req.body.longitude,
address:req.body.address
});
CreatePackage.save()
.then(data =>{
res.json(data)
})
.catch(error =>{
res.json(error)
})
});
//k-means
var clusters = require('./clustering.js');
router.post('/grouporders', clusters.groupOrders);
module.exports = router
// const bcrypt = require('bcrypt');
// class Router {
// constructor(app,db) {
// this.login(app, db);
// this.logout(app, db);
// this.isLoggedIn(app, db);
// }
// login(app,db) {
// app.post('/login', (req, res) => {
// let username = req.body.username;
// let password = <PASSWORD>;
// username = username.toLoweCase();
// if (username.length > 12 || password.length > 12) {
// res.json({
// success: false,
// msg: 'An error occured, please try again'
// })
// return;
// }
// let cols = [username];
// db.query('SELECT * FROM user WHERE username = ? LIMIT 1', cols, (err, data, fields) => {
// if(err) {
// res.json({
// success: false,
// msg: 'An error occurede, please try again'
// })
// return;
// }
// }); //Found 1 user with this username
// if (data && data.length === 1) {
// bcrypt.compare(password, data[0].password, (bcryptErr, verified) => {
// if(verified) {
// req.session.userID = data[0].id;
// res.json({
// success: true,
// username: data[0].username
// })
// return;
// }
// else {
// res.json({
// success: false,
// msg: 'Invalid password'
// })
// }
// });
// } else {
// res.json({
// success: false,
// msg: 'User not found, please try again'
// })
// }
// });
// }
// logout(app,db) {
// app.post('/logout', (req, res) => {
// if(req.session.userID) {
// req.session.destroy();
// res.json({
// success: true
// })
// return true;
// } else {
// res.json({
// success: false
// })
// return false;
// }
// });
// }
// isLoggedIn(app,db) {
// app.post('/isLoggedIn', (req, res) => {
// if(req.session.userID) {
// let cols = [req.session.userID];
// db.query('SELECT * FROM user WHERE id = ? LIMIT 1', cols, (err, data, fields) => {
// if(data && data.length === 1) {
// res.json ({
// success: true,
// username: data[0].username
// })
// return true;
// } else {
// res.json({
// success: false
// })
// }
// });
// }
// else {
// res.json({
// success: false
// })
// }
// });
// }
// }
// module.exports = Router;<file_sep>/backend/server.js
const express = require('express')
const app = express()
const mongoose = require("mongoose")
const dotenv = require('dotenv')
const routesUrls = require('./Router')
const cors = require('cors')
//////////chat////////
// const server = require('http').createServer(app)
// const io = require('socket.io')(server)
// const socketManage = require('./socketManage')(io)
// const PORT = process.env.PORT || 80
// const path = require('path')
// io.on('connection', socketManage )
// // In dev mode just hide hide app.uss(... ) below
// //app.use( express.static(path.join(__dirname, '../build')))
// server.listen( PORT, () => console.log('App was start at port : ' + PORT ))
//////////chat////////
dotenv.config()
mongoose.connect(process.env.DATABASE_ACCESS, () => console.log("DataBase connected"))
//let db = mongo.createConnection("mongodb+srv://naomies:[email protected]/myFirstDataBase?retryWrites=true&w=majority", {useNewUrlParser: true}); //or connect()
const passport = require("passport");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const session = require("express-session");
// Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(
cors({
origin: "http://localhost:3000", // <-- location of the react app were connecting to
credentials: true,
})
);
app.use(
session({
secret: "secretcode",
resave: true,
saveUninitialized: true,
})
);
app.use(cookieParser("secretcode"));
app.use(passport.initialize());
app.use(passport.session());
require("./passportConfig")(passport);
//end of middleware
app.use(express.json())
app.use(cors()) //initialize
app.use('/app', routesUrls) //exactly
app.listen(4000, ()=>console.log("server is running")) | b1a41af8dcd59e809bf45e6bec79221ade25933f | [
"JavaScript"
] | 4 | JavaScript | Naomie-Sebag/web_react_project | 6b525734798944bdee6316c81ad7edf1a98c5d5c | bcffb2406b39f9f5b30bc21c3ba43fde4ab79483 | |
refs/heads/master | <file_sep>package com.thoughtworks.interview.utils;
import java.math.BigDecimal;
import com.thoughtworks.interview.model.Discount;
import com.thoughtworks.interview.model.Item;
import com.thoughtworks.interview.model.Membership;
/**
* Calculate item price
*
* @author WeiWei
*
*/
public class DiscountCalculator {
public static double getSubTotal(Item item, int qty) {
return getSubTotal(item, qty, null);
}
public static double getSavings(Item item, int qty) {
return getSavings(item, qty, null);
}
public static double getSubTotal(Item item, int qty, Membership member) {
double sub_total = 0;
switch (item.getDiscount()){
case ALLSALE:
if (qty > 2) {
sub_total = chargeBuyTwoGetOneFree(item, qty, member);
} else {
sub_total = chargeFivePercentOff(item, qty, member);
}
break;
case BUYTWOGETONEFREE:
sub_total = chargeBuyTwoGetOneFree(item, qty, member);
break;
case FIVEPERCENTOFF:
sub_total = chargeFivePercentOff(item, qty, member);
break;
default:
sub_total = item.getPrice() * qty;
break;
}
return sub_total;
}
public static double getSavings(Item item, int qty, Membership member) {
double savings;
/**
* If item is available for both two sale, when item match buy two get
* another free condition, use this rule then use 5% off rule.
*/
switch (item.getDiscount()) {
case BUYTWOGETONEFREE:
savings = saveBuyTwoGetOneFree(item, qty, member);
break;
case FIVEPERCENTOFF:
savings = saveFivePercentOff(item, qty, member);
break;
case ALLSALE:
if (qty > 2) {
savings = saveBuyTwoGetOneFree(item, qty, member);
} else {
savings = saveFivePercentOff(item, qty, member);
}
break;
default:
savings = 0;
break;
}
return savings;
}
private static double chargeFivePercentOff(Item item, int qty,Membership member) {
double sub_total;
if(null == member){
member = Membership.NOMEMBER;
}
if(member.toString() == "NORMALMEMBER"){
sub_total = item.getPrice() * qty * Math.min(Discount.FIVEPERCENTOFF.getRate(), member.getRate());
}else{
sub_total = item.getPrice() * qty * Discount.FIVEPERCENTOFF.getRate() * member.getRate();
}
return sub_total;
}
private static double chargeBuyTwoGetOneFree(Item item, int qty,Membership member) {
double sub_total =item.getPrice() * (qty - Math.ceil(qty / 3));
if(null != member && member.toString() == "GOLDMEMBER"){
sub_total = sub_total * member.getRate();
}
return sub_total;
}
public static double saveFivePercentOff(Item item, int qty, Membership member) {
if(null == member){
member = Membership.NOMEMBER;
}
double savings = item.getPrice() * qty * new BigDecimal(1-Discount.FIVEPERCENTOFF.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
switch (member) {
case GOLDMEMBER:
savings += (item.getPrice() * qty - savings) * new BigDecimal(1-member.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
break;
default:
savings = item.getPrice() * qty * new BigDecimal(1-Math.min(Discount.FIVEPERCENTOFF.getRate(), member.getRate())).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
break;
}
return savings;
}
private static double saveBuyTwoGetOneFree(Item item, int qty, Membership member) {
double savings = item.getPrice() * Math.ceil(qty / 3);
if(null != member && member.toString() == "GOLDMEMBER"){
savings += (item.getPrice() * qty - savings) * new BigDecimal(1-member.getRate()).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
}
return savings;
}
}
<file_sep>package com.thoughtworks.interview.model;
public enum Discount {
NODISCOUNT(1),FIVEPERCENTOFF(0.95),BUYTWOGETONEFREE(0.3),ALLSALE(0);
private double rate;
private Discount(double rate){
this.setRate(rate);
}
public static Discount nameOf(String name){
if(name.toLowerCase().equals("fivepercentoff")){
return FIVEPERCENTOFF;
}
if(name.toLowerCase().equals("buytwogetonefree")){
return BUYTWOGETONEFREE;
}
if(name.toLowerCase().equals("allsale")){
return ALLSALE;
}
return NODISCOUNT;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}
<file_sep>package com.thoughtworks.interview.service;
import java.util.List;
import com.thoughtworks.interview.exception.ItemNotExsitException;
import com.thoughtworks.interview.model.Discount;
import com.thoughtworks.interview.model.Item;
/**
* Basic item operation services
* @author WeiWei
*
*/
public interface ItemService {
/**
* Set discount type
* @param itemSerial
* @param discount
* @return
*/
boolean setDiscount(String itemSerial,Discount discount) throws ItemNotExsitException;
/**
* Get all items
* @return
*/
List<Item> getItems();
/**
* Get an item by item serial
* @param itemSerial
* @return
* @throws ItemNotExsitException
*/
Item getItem(String itemSerial) throws ItemNotExsitException;
}
<file_sep>package com.thoughtworks.interview.utils;
import java.lang.reflect.Member;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.thoughtworks.interview.model.Discount;
import com.thoughtworks.interview.model.Item;
import com.thoughtworks.interview.model.Membership;
public class DiscountCalculatorTest {
private static Item item;
@Before
public void init(){
item = new Item("足球", 99.00, "个","运动用品", "ITEM0000001");
}
@After
public void end(){
item = null;
}
@Test
public void testTwoDiscount() {
int qty = 3;
double sub_total;
double savings;
item.setDiscount(Discount.ALLSALE);
/**
* If quantity equals or is greater than three, item matches buy two get another one free rule.
*/
sub_total = DiscountCalculator.getSubTotal(item,qty);
savings = DiscountCalculator.getSavings(item, qty);
Assert.assertNotEquals(sub_total, item.getPrice() * qty);
Assert.assertEquals(item.getPrice()*qty, sub_total + savings,0);
/**
* If quantity is less than three, item matches 5% off rule.
*/
qty = 2;
sub_total = DiscountCalculator.getSubTotal(item,qty);
savings = DiscountCalculator.getSavings(item, qty);
Assert.assertEquals(sub_total, item.getPrice()*qty*0.95,0);
}
/**
* 5% Off
*/
@Test
public void testFivePercentOff() {
double sub_total;
double savings;
int qty = 3;
item.setDiscount(Discount.FIVEPERCENTOFF);
sub_total = DiscountCalculator.getSubTotal(item,qty);
savings = DiscountCalculator.getSavings(item, qty);
Assert.assertEquals(sub_total, item.getPrice()*qty*0.95,0.001);
Assert.assertEquals(item.getPrice()*qty*0.05, savings,0.001);
}
/**
* Buy two get another same one free
*/
@Test
public void testBuyTwoGetOneFree() {
int qty = 3;
double sub_total;
double savings;
item.setDiscount(Discount.BUYTWOGETONEFREE);
sub_total = DiscountCalculator.getSubTotal(item,qty);
savings = DiscountCalculator.getSavings(item, qty);
Assert.assertNotEquals(sub_total, item.getPrice() * qty);
Assert.assertEquals(item.getPrice()*qty, sub_total + savings,0);
qty = 5;
sub_total = DiscountCalculator.getSubTotal(item,qty);
savings = DiscountCalculator.getSavings(item, qty);
Assert.assertEquals(sub_total,item.getPrice() * (qty - Math.ceil(qty/3)),0);
Assert.assertEquals(savings,item.getPrice() * Math.ceil(qty/3),0);
}
/**
* No sale
*/
@Test
public void testNoDiscount() {
int qty = 3;
double sub_total = DiscountCalculator.getSubTotal(item, qty);
double savings = DiscountCalculator.getSavings(item, qty);
Assert.assertTrue(sub_total == item.getPrice() * qty);
Assert.assertEquals(Double.parseDouble("0.0"), savings,0);
}
@Test
public void testFivePercentOffWithMembership(){
//normal membership
item.setDiscount(Discount.FIVEPERCENTOFF);
int qty = 3;
double sub_total = DiscountCalculator.getSubTotal(item, qty, Membership.NORMALMEMBER);
double savings = DiscountCalculator.getSavings(item, qty, Membership.NORMALMEMBER);
Assert.assertEquals(261.36, sub_total,1e-6);
Assert.assertEquals(35.64, savings,1e-6);
//gold membership
sub_total = DiscountCalculator.getSubTotal(item, qty, Membership.GOLDMEMBER);
savings = DiscountCalculator.getSavings(item, qty, Membership.GOLDMEMBER);
Assert.assertEquals(211.6125, sub_total,1e-6);
Assert.assertEquals(85.3875, savings,1e-6);
}
@Test
public void testBuyTwoGetOneFreeWithMembership(){
//normal membership
item.setDiscount(Discount.BUYTWOGETONEFREE);
int qty = 3;
double sub_total = DiscountCalculator.getSubTotal(item, qty, Membership.NORMALMEMBER);
double savings = DiscountCalculator.getSavings(item, qty, Membership.NORMALMEMBER);
Assert.assertEquals(198, sub_total,1e-6);
Assert.assertEquals(99, savings,1e-6);
//gold membership
sub_total = DiscountCalculator.getSubTotal(item, qty, Membership.GOLDMEMBER);
savings = DiscountCalculator.getSavings(item, qty, Membership.GOLDMEMBER);
Assert.assertEquals(148.5, sub_total,1e-6);
Assert.assertEquals(148.5, savings,1e-6);
}
}
<file_sep>package com.thoughtworks.interview.model;
public enum Membership {
NOMEMBER(1),NORMALMEMBER(0.88),GOLDMEMBER(0.75);
private double rate;
private Membership(double rate) {
this.setRate(rate);
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
}
<file_sep>package com.thoughtworks.interview.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.math.NumberUtils;
import com.alibaba.fastjson.JSONObject;
public class CommonTools {
/**
* Convert inputed string to Json object
* @param str ['itemName','itemName',...]
* @return {"itemName":amount,...}
*/
public static JSONObject StringtoJson(String str){
String regex = "'[^']+'";
Matcher m = Pattern.compile(regex).matcher(str);
ArrayList<String> al = new ArrayList<String>();
while(m.find()){
al.add(m.group(0).replace("'", ""));
}
/*
* Filter same element
*/
HashSet<String> hs=new HashSet<String>(al);
Map<String, Object> map = new HashMap<String, Object>();
for(Iterator<String> it=hs.iterator();it.hasNext();){
int count = 0;
String key = it.next().toString().replace("'", "");
for(int i =0;i<al.size();i++){
if(key.equals(al.get(i))){
count++;
}
}
if(key.contains("-")){
count = NumberUtils.toInt(key.split("-")[1]);
key = key.split("-")[0];
}
map.put(key, count);
}
return new JSONObject(map);
}
/**
* To identify the result of division
* @param d1 result of division
* @return
*/
public static boolean isExactDivision(double d1){
return d1 == Math.floor(d1) && d1 > 0.00;
}
}
<file_sep>package com.thoughtworks.interview.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* Character encoding interceptor
* @author WeiWei
*
*/
public class CharacterEncodingInterceptor implements HandlerInterceptor{
private String characterEncoding = "utf-8";
public String getCharacterEncoding() {
return characterEncoding;
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object object)
throws Exception {
request.setCharacterEncoding(characterEncoding);
return true;
}
@Override
public void postHandle(HttpServletRequest paramHttpServletRequest,
HttpServletResponse paramHttpServletResponse, Object paramObject,
ModelAndView paramModelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest paramHttpServletRequest,
HttpServletResponse paramHttpServletResponse, Object paramObject,
Exception paramException) throws Exception {
// TODO Auto-generated method stub
}
}
<file_sep>package com.thoughtworks.interview.exception;
public class ItemNotExsitException extends Exception {
/**
*
*/
private static final long serialVersionUID = -6908756668840994884L;
public ItemNotExsitException(){
super();
}
public ItemNotExsitException(String msg){
super(msg);
}
}
<file_sep>package com.thoughtworks.interview.utils;
import org.junit.Assert;
import org.junit.Test;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class CommonToolsTest {
@Test
public void testStringToJson(){
String str = "['ITEM000001','ITEM000001','ITEM000001', 'ITEM000001', 'ITEM000001', 'ITEM000003-2', 'ITEM000005'," +
" 'ITEM000005','ITEM000005']";
String expectStr = "{\"ITEM000005\":3,\"ITEM000003\":2,\"ITEM000001\":5}";
JSONObject json = JSON.parseObject(expectStr);
Assert.assertEquals(json, CommonTools.StringtoJson(str));
}
@Test
public void testIsExactDivision(){
double d1 = 2.0;
double d2 = 2.5;
Assert.assertTrue(CommonTools.isExactDivision(d1));
Assert.assertTrue(!CommonTools.isExactDivision(d2));
}
}
<file_sep>package com.thoughtworks.interview.service.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.thoughtworks.interview.exception.ItemNotExsitException;
import com.thoughtworks.interview.model.Discount;
import com.thoughtworks.interview.model.Item;
import com.thoughtworks.interview.service.ItemService;
public class ItemServiceImpl implements ItemService {
/**
* Default item list
*/
private static Map<String,Item> DEFAULT_ITEM_MAP = new HashMap<String, Item>();
static{
DEFAULT_ITEM_MAP.put("ITEM0000001",new Item("足球", 99.00, "个","运动用品", "ITEM0000001"));
DEFAULT_ITEM_MAP.put("ITEM0000002",new Item("篮球", 99.00, "个", "运动用品", "ITEM0000002"));
DEFAULT_ITEM_MAP.put("ITEM0000003",new Item("羽毛球", 5.00, "个", "运动用品", "ITEM0000003"));
DEFAULT_ITEM_MAP.put("ITEM0000004",new Item("乒乓球", 4.00, "个", "运动用品", "ITEM0000004"));
DEFAULT_ITEM_MAP.put("ITEM0000005",new Item("足球鞋", 300.00, "双", "运动鞋类", "ITEM0000005"));
DEFAULT_ITEM_MAP.put("ITEM0000006",new Item("篮球鞋", 400.00, "双", "运动鞋类", "ITEM0000006"));
DEFAULT_ITEM_MAP.put("ITEM0000007",new Item("羽毛球鞋", 500.00, "双", "运动鞋类", "ITEM0000007"));
DEFAULT_ITEM_MAP.put("ITEM0000008",new Item("乒乓球鞋", 300.00, "双", "运动鞋类", "ITEM0000008"));
DEFAULT_ITEM_MAP.put("ITEM0000009",new Item("羽毛球球拍", 650.00, "副", "运动用品", "ITEM0000009"));
DEFAULT_ITEM_MAP.put("ITEM0000010",new Item("乒乓球球拍", 99.00, "副", "运动用品", "ITEM0000010"));
DEFAULT_ITEM_MAP.put("ITEM0000011",new Item("苹果", 3.00, "斤", "水果", "ITEM0000011"));
DEFAULT_ITEM_MAP.put("ITEM0000012",new Item("香蕉", 4.00, "斤", "水果", "ITEM0000012"));
}
@Override
public boolean setDiscount(String itemSerial, Discount discount) throws ItemNotExsitException {
if(!DEFAULT_ITEM_MAP.containsKey(itemSerial)){
throw new ItemNotExsitException();
}
Item item = DEFAULT_ITEM_MAP.get(itemSerial);
item.setDiscount(discount);
DEFAULT_ITEM_MAP.put(itemSerial, item);
return true;
}
@Override
public List<Item> getItems() {
List<Item> items = new ArrayList<Item>();
for(String key:DEFAULT_ITEM_MAP.keySet()){
items.add(DEFAULT_ITEM_MAP.get(key));
}
return items;
}
@Override
public Item getItem(String itemSerial) throws ItemNotExsitException {
if(!DEFAULT_ITEM_MAP.containsKey(itemSerial)){
throw new ItemNotExsitException();
}
return DEFAULT_ITEM_MAP.get(itemSerial);
}
}
| 819be94ae5133a14bdbd95255faf6cb9ff428024 | [
"Java"
] | 10 | Java | LamarWei/thoughtworks-assignment | 14ca024c4fb549ab35a803e5d0856d0415a8e1bd | 17d694b391f2691ec43da4c0bbc5a726e030c853 | |
refs/heads/master | <file_sep>class Sensor {
constructor( ship, map ) {
this.map = map;
this.ship = ship;
this.level = 1;
this.ScanCP = 2;
}
use () {
this.ship.supplies -= 2; // consume 2% of supplies
}
getInfo () {
}
upgrade () {
if ( this.level == 1 && this.ship.credit > 100 ) {
this.ship.credit -= 100;
this.level = 2;
this.ScanCP = 5;
}
}
}
// the sensors needed to be commented out as the game would not start with this code
/*
function Sensors(ship,sensors_tpye, gameMap)
{
shipSupplies = shipSupplies-2;
len sensorText = document.getElementById("sensor_message").textContext
sensorText = null;
if(sensors_type == 1) <!-- basic -->
{
var i;
var j;
for(obj in gameMap){
for(i=ship.x-2;i<ship.x+2;i++){
for(j=ship.y-2;j<ship.y+2;j++){
if(i==gameMap[obj].x && j==gameMap[obj].y){
sensorText += gameMap[obj].name;
}
else
break;
}
}
}
}
else if(sensors_tpye == 2)// <!-- enhanced -->
{
var i;
var j;
for(obj in gameMap){
for(i=ship.x-5;i<ship.x+5;i++){
for(j=ship.y-5;j<ship.y+5;j++){
if(i==ship.x-5 && j==ship.y+4)
continue;
if(i==ship.x-5 &&j==ship.y+5)
continue;
if(i==ship.x-5 &&j==ship.y-4)
continue;
if(i==ship.x-5 &&j==ship.y-5)
continue;
if(i==ship.x+5 && j==ship.y+4)
continue;
if(i==ship.x+5 &&j==ship.y+5)
continue;
if(i==ship.x+5 &&j==ship.y-4)
continue;
if(i==ship.x+5 &&j==ship.y-5)
continue;
if(i==ship.x-4 &&j==ship.y+5)
continue;
if(i==ship.x-4 &&j==ship.y-5)
continue;
if(i==ship.x+4 &&j==ship.y+5)
continue;
if(i==ship.x+4 &&j==ship.y-5)
continue;
if(i==gameMap[obj].x && j==gameMap[obj].y){
sensorText += gameMap[obj].name;
}
else
break;
}
}
}
}
}
*/
<file_sep>//<!-- SH-6 Sensors High-->
//<!-- I want to see what located at nearby Celectial Points,so I Know where things are -->
//<!-- IN PROGRESS>
function Sensors2(Ship, Celestial_Map)
{
let sensorText = document.getElementById("sensor_message").textContent;
sensorText = null;
for(obj in Celestial_Map)
{
if (distance(Ship, Celestial_Map[obj]) < 100)
{
sensorText += Celestial_Map[obj].name;
}
}
}
<<<<<<< HEAD
=======
<!-- IN PROGRESS -->
>>>>>>> 7277d5ede67621faa91b0c48f40a1fa4d30c287f
function distance(obj1, obj2)
{
let dist_sq = Math.abs(obj1.x - obj2.x) + Math.abs(obj1.y - obj2.y);
return Math.sqrt(dist_sq);
}
function Sensors(currX,currY,supplies, sensors_tpye, Celestial_Map)
{
alert("you deploys sensors for current cp");
<<<<<<< HEAD
supplies = supplies-2;
if(sensors_type == 1)// <!-- basic -->
=======
supplies = supplies-2;
if(sensors_type == 1) <!-- basic -->
>>>>>>> 7277d5ede67621faa91b0c48f40a1fa4d30c287f
{
var i;
var j;
for(i=currX-2;i<currX+2;i++){
for(j=currY-2;j<currY+2;j++){
if(i==celestialX && j==celestialY){
//check if (celestialX,celestialY) in Celestial_map
//add all new (celestialX,celestialY) in Celestial Map
//display current CP
}
else
break;
}
}
}
else if(sensors_tpye == 2)// <!-- enhanced -->
{
var i;
var j;
for(i=currX-5;i<currX+5;i++){
for(j=currY-5;j<currY+5;j++){
if(i==currX-5 && j==currY+4)
continue;
if(i==currX-5 &&j==currY+5)
continue;
if(i==currX-5 &&j==currY-4)
continue;
if(i==currX-5 &&j==currY-5)
continue;
if(i==currX+5 && j==currY+4)
continue;
if(i==currX+5 &&j==currY+5)
continue;
if(i==currX+5 &&j==currY-4)
continue;
if(i==currX+5 &&j==currY-5)
continue;
if(i==currX-4 &&j==currY+5)
continue;
if(i==currX-4 &&j==currY-5)
continue;
if(i==currX+4 &&j==currY+5)
continue;
if(i==currX+4 &&j==currY-5)
continue;
if(i==celestialX && j==celestialY){
//check if (celestialX,celestialY) in Celestial_map
//add all new (celestialX,celestialY) in Celestial Map
//display current CP
}
else
break;
}
}
}
}
//how to get all celestialX,celestialY form map (read file??)
//how to check if in celestial map and add to the Celestial map
//consider different direction
//every direction search 5 ,like a circle
<file_sep>// saves the player's name
const nameInput = document.querySelector('#playerName');
// MAIN VARIABLES; (globals, in a sense)
window.gameData = {
mapsize: 128,
celeron: null,
xeon: null,
ryzen: null,
eniac: null,
badMax: new Array(2),
recipe: new Array(2),
abFreighter: [],
asteroid: [],
meteorShower: [],
asteroidRandom: true,
meteorRandom: true,
freighterRandom: true,
stationRandom: true,
gaze: { length: 0 },
msgs: [],
savedGamed: false,
shipX: 0,
shipY: 0,
shipEnergy: 1000,
shipSupplies: 100,
shipCredit: 1000,
shipEngineLv: 1,
shipDamaged: false,
shipNormalPlay: true,
randomWormhole: false,
};
// when the window intially opens, this is what happens
window.onload = function() {
// populate the map
populateSavedGameList();
// start the game
let setupPage = document.querySelectorAll('.setup-game')[0];
// initializes default settings
document.querySelectorAll('.game-start-btn')[0].onclick = function() {
initGame();
setupPage.attributes.class.value += ' hide';
};
// initializes map and ship from previous game if the previous game exists
document.querySelectorAll('.game-cont-btn')[0].onclick = function() {
if (contGame()) {
setupPage.attributes.class.value += ' hide';
}
};
};
// initializes the game
function initGame () {
if (window.gameData != undefined) {
window.gameMap = new GameMap(window.gameData.mapsize);
window.oldSpice = new Ship(
window.gameData.shipX,
window.gameData.shipY,
window.gameData.shipEnergy,
window.gameData.shipSupplies,
window.gameData.shipCredit,
window.gameData.shipEngineLv,
window.gameData.shipDamaged,
window.gameData.shipNormalPlay
);
} else { // default settings
window.gameMap = new GameMap(128);
window.oldSpice = new Ship(0, 0, 1000, 100, 1000, 1, false, true);
}
// setup + save game
gameSetSave();
// update screen data
updateHeading();
updateLevels();
PopulateMap(window.gameMap);
// render map
window.gameMap.renderMap(window.oldSpice.x, window.oldSpice.y);
ctrecipe.tickObjects.push(function() { HitObj(window.oldSpice.x, window.oldSpice.y); } );
ctrecipe.tick();
}
// continues a saved game; Sprint 2
function contGame () {
}
// set up the game; save the game; could be discarded; Sprint 2
function gameSetSave () {
}
// add planet locations to the left panel on the main game playing page
function gazePopulate ( obj, objX, objY, isToSave ) {
}
// add planet locations to the saved game; adds to the list which is to
// be displayed on the left panel on the main game playing page
function populateSavedGaze ( gaze ) {
}
// save the message board; used to save alerts for the game to be played
// at a later time
function saveMessageBoard(newMessage) {
let msgIndex = window.gameData.msgs.length;
window.gameData.msgs[msgIndex] = newMessage;
}
// populates message board; shows the alerts that are generated
function populateMessageBoard(savedMessages) {
for (const msg of savedMessages)
addMessage(msg);
}
// shows saved games on the main menu screen
function populateSavedGameList () {
}
// update the player name input box when a past game has been selected
function updatePlayerNameField ( selectedGamed ) {
}
<file_sep>/* Add items to the map */
function PopulateMap(gameMap) {
// to be reimplemented
generateCeleron(gameMap);
generateXeon(gameMap);
generateRyzen(gameMap);
generateEniac(gameMap);
// load objects; asteroid, stations, freighters, other celestial objects
// * ASTEROID *
if (window.gameData.asteroidRandom) {
for(let i = 0; i < 10; ++i) {
let objCoordx = Math.ceil(Math.random() * (gameMap.size));
let objCoordy = Math.ceil(Math.random() * (gameMap.size));
generateCelestialObjects(gameMap, 4, objCoordx, objCoordy);
}
} else {
for(let coords of window.gameData.asteroids) {
let objCoordx = coords[0];
let objCoordy = coords[1];
generateCelestialObjects(gameMap, 4, objCoordx, objCoordy);
}
}
// * METEOR SHOWERS *
if(window.gameData.meteorRandom) {
for(let i = 0; i < 10; ++i) {
let objCoordx = Math.ceil(Math.random() * (gameMap.size));
let objCoordy = Math.ceil(Math.random() * (gameMap.size));
generateCelestialObjects(gameMap, 4, objCoordx, objCoordy);
}
} else {
for(let coords of window.gameData.meteors) {
let objCoordx = coords[0];
let objCoordy = coords[1];
generateCelestialObjects(gameMap, 4, objCoordx, objCoordy);
}
}
// * FREIGHTERS *
if (window.gameData.freighterRandom) {
for(let i = 0; i < 10; ++i) {
let objCoordx = Math.ceil(Math.random() * (gameMap.size));
let objCoordy = Math.ceil(Math.random() * (gameMap.size));
generateCelestialObjects(gameMap, 4, objCoordx, objCoordy);
}
} else {
for(let coords of window.gameData.freighters) {
let objCoordx = coords[0];
let objCoordy = coords[1];
generateCelestialObjects(gameMap, 4, objCoordx, objCoordy);
}
}
// * STATIONS *
if (window.gameData.stationRandom) {
for(let i = 0; i < 10; ++i) {
let objCoordx = Math.ceil(Math.random() * (gameMap.size));
let objCoordy = Math.ceil(Math.random() * (gameMap.size));
generateCelestialObjects(gameMap, (i % 4), objCoordx, objCoordy);
}
} else {
for(let coords of window.gameData.stations) {
let objCoordx = coords[0];
let objCoordy = coords[1];
let stationType = Math.floor(Math.random() * 4);
generateCelestialObjects(gameMap, stationType, objCoordx, objCoordy);
}
}
}
/* populates a saved map with the state it was left in */
function PopulateSavedMap ( gameMap, savedMap ) {
}
/* generates celestial objects */
function generateCelestialObjects ( gameMap, type, celestX, celestY ) {
switch ( type ) {
case 0:
mapObj = new SpaceStation( [new MuskTesla( 100, 1000 ), new RepairDepot, new MiniMart()] );
break;
case 1:
mapObj = new SpaceStation( [new MuskTesla( 100, 1000 ), new RepairDepot()] );
break;
case 2:
mapObj = new SpaceStation( [new MuskTesla( 100, 1000 ), new MiniMart()] );
break;
case 3:
mapObj = new SpaceStation( [new MuskTesla( 100, 1000 )] );
break;
case 4:
mapObj = new Asteroid();
break;
case 5:
mapObj = new AbFreighter();
break;
case 6:
mapObj = new MeteorShower();
break;
}
/* save the current state of the game */
function updateLogs ( gameMap, mapObj, objCoordX, objCoordY ) {
console.log( 'Placed ' + mapObj.objType + " at position: " + objCoordX + ' ' + objCoordY );
gameMap.add( mapObj, objCoordX, objCoordY );
saveMap( gameData, mapObj, objCoordX, objCoordY );
}
// * CELERON *
// generate celeron at a random x and y position, call the
// generateCeleronAtLocation function to actually place Celeron
// on the map
function generateCeleron( gameMap ) {
let randomCelX = Math.ceil(Math.random() * (gameMap.size));
let randomCelY = Math.ceil(Math.random() * (gameMap.size));
generateCeleronAtLocation(gameMap, randomCelX, randomCelY);
}
// places Celeron on the map
function generateCeleronAtLocation(gameMap, celeronCoordX, celeronCoordY) {
// if the location has nothing, add Celeron to the map
mapObj = new Celeron();
if (gameData.celeronX || gameData.celeronX === 0)
celeronCoordX = gameData.celeronX;
if (gameData.celeronY || gameData.celeronY === 0)
celeronCoordY = gameData.celeronY;
mapObj.x = celeronCoordX;
mapObj.y = celeronCoordY;
updateLogs(gameMap, mapObj, celeronCoordX, celeronCoordY);
gazePopulate(mapObj, celeronCoordX, celeronCoordY);
}
// * ENIAC *
// generate eniac at a random x and y position, call the
// generateEniacAtLocation function to actually place eniac
// on the map
function generateEniac ( gameMap ) {
generateEniacAtLocation(gameMap, 0, 0);
}
// places Eniac on the map
function generateEniacAtLocation(gameMap, eniacCoordX, eniacCoordY) {
mapObj = new Eniac();
mapObj.x = eniacCoordX;
mapObj.y = eniacCoordY;
updateLogs( gameMap, mapObj, eniacCoordX, eniacCoordY );
}
// * XEON *
// generate xeon at a random x and y position, call the
// generateXeonAtLocation function to actually place Xeon
// on the map
function generateXeon(gameMap) {
let randomXeonX = Math.ceil(Math.random() * (gameMap.size));
let randomXeonY = Math.ceil(Math.random() * (gameMap.size));
generateXeonAtLocation(gameMap, randomXeonX, randomXeonY)
}
// places Xeon on the map
function generateXeonAtLocation(gameMap, xeonCoordX, xeonCoordY) {
mapObj = new Xeon();
if ( gameData.xeonX || gameData.xeonX === 0 )
xeonCoordX = gameData.xeonX;
if ( gameData.xeonY || gameData.xeonY === 0 )
xeonCoordY = gameData.xeonY;
mapObj.x = xeonCoordX;
mapObj.y = xeonCoordY;
updateLogs(gameMap, mapObj, xeonCoordX, xeonCoordY);
gazePopulate(mapObj, xeonCoordX, xeonCoordY);
}
// * RYZEN *
// generate ryzen at a random x and y position, call the
// generateRyzenAtLocation function to actually place Ryzen
// on the map
function generateRyzen ( gameMap ) {
let randomRyzenX = Math.ceil(Math.random() * (gameMap.size));
let randomRyzenY = Math.ceil(Math.random() * (gameMap.size));
generateRyzenAtLocation(gameMap, randomRyzenX, randomRyzenY)
}
// places Ryzen on the map
function generateRyzenAtLocation(gameMap, ryzenCoordX, ryzenCoordY) {
mapObj = new Ryzen();
if(gameData.ryzenX || gameData.ryzenX === 0)
ryzenCoordX = gameData.ryzenX;
if(gameData.ryzenY || gameData.ryzenY === 0)
ryzenCoordY = gameData.ryzenY;
mapObj.x = ryzenCoordX;
mapObj.y = ryzenCoordY;
updateLogs(gameMap, mapObj, ryzenCoordX, ryzenCoordY);
gazePopulate(mapObj, ryzenCoordX, ryzenCoordY);
}
<file_sep>/* sees if OldSpice encounters any objects */
// could potentially be discarded
var HitObj = function(x_coord, y_coord) {
}
<file_sep>/* admin page */
<file_sep>function saveMap(gameData, mapObj, objX, objY){
}
function saveShip(gameData, oldSpice){
}
<file_sep><!-- SH-10 Encountering an Abandoned Freighter Low -->
<!-- Storys: As a player, I want to encounter an abandoned
Freighter drifting in space so I can take on additional supplies and energy -->
function Freighter(energy,supplies)
{
energy = energy + 10;
supplies = supplies + 10;
return {a1:energy,b1:supplies};
}
<!-- call fucntion -->
//var obj = Freighter(energy,supplies)
//energy = obj.a1;
//supplies = obj.b1;
//energy and supplies is global variable<file_sep>/* Information for the objects that the game has */
// MAP OBJECT
function MapObject(type, radius) {
this.objType = type;
this.radius = radius;
this.isHidden = false;
}
MapObject.prototype.Collide = function() {
console.log("collision noted");
}
// ASTEROID
function Asteroid() {
}
Asteroid.prototype = new MapObject('Asteroid', 0);
Asteroid.prototype.DamageShip = function() {
alert("OldSpice bare missed an asteroid! Damage occurred!");
oldSpice.isDamaged = true;
}
Asteroid.prototype.DestroyShip = function() {
oldSpice.energy = 0;
ctrecipe.GameOver("OldSpice hit an asteroid! You blew up!");
}
Asteroid.prototype.Collide = function() {
MapObejct.prototype.Collide.call(this);
let eventDecider = Math.random();
if(eventDecider < 0.9) {
this.DamageShip();
}
else {
this.DestroyShip();
}
}
// METEOR SHOWER
function MeteorShower() {
}
MeteorShower.prototype = new MapObject("MeteorShower", 0);
MeteorShower.prototype.Collide = function() {
MapObject.prototype.Collide.call(this);
alert("You flew into a meteor shower and OldSpice is damaged!");
oldSpice.isDamaged = true;
}
// ABANDONED FREIGHTER
function AbFreighter() {
}
AbFreighter.prototype = new MapObject("AbFreighter", 0);
AbFreighter.prototype.Loot = function() {
let maxEnergy = 1000;
let maxSupply = 100;
let retEnergy;
let retSupply;
let roll = Math.random();
if (roll < 0.75) {
retEnergy = 0.1 * maxEnergy;
retSupply = 0.1 * maxSupply;
}
else if (roll < 0.90) {
retEnergy = 0.5 * maxEnergy;
retSupply = 0.5 * maxSupply;
}
else {
retEnergy = maxEnergy;
retSupply = maxSupply;
}
return [retEnergy, retSupply];
}
AbFreighter.prototype.Collide = function() {
MapObject.prototype.Collide.call(this);
let loot = this.Loot();
lootEnergy = parseInt(loot[0]);
lootSupply = parseInt(loot[1]);
alert("You came across an abandoned freighter and collected " + lootEnergy + " energy and " + lootSupply + " supply from the remains!" );
oldSpice.energy += lootEnergy;
if (oldSpice.supplies + lootSupply <= 100)
oldSpice.supplies += lootSupply;
else
oldSpice.supplies = 100;
updateLevels(); // display new supply and energy gained from the freighter
gameMap.remove(oldSpice.x, oldSpice.y); // remove the freighter from the map since it was already used
}
// WORMHOLE
function WormHole() {
}
WormHole.prototype = new MapObject("Wormhole", 0);
WormHole.prototype.Collide = function() {
MapObject.prototype.Collide.call(this);
alert("You hit a wormhole!");
if(ctrecipe.WormholeFixed) {
oldSpice.x = ctrecipe.WormholeX;
oldSpice.y = ctrecipe.WormholeY;
}
// relocate after falling into a wormhole
else {
xrand = Math.ceil(Math.random() * (gameMap.size - 2));
yrand = Math.ceil(Math.random() * (gameMap.size - 2));
oldSpice.x = xrand;
oldSpice.y = yrand;
}
}
// PLANET
function Planet(name, x, y) {
this.name = name;
this.x = x;
this.y = y;
}
Planet.prototype = new MapObject('Planet', 1);
Planet.prototype.Collide = function() {
}
Planet.prototype.EnterOrbit = function() {
}
// ENIAC
function Eniac () {
};
Eniac.prototype = new Planet('Eniac', -1, -1);
Eniac.prototype.Collide = function() {
MapObject.prototype.Collide.call(this);
if(oldSpice.recipe) {
ctrecipe.GameWinner("You got the KokaKola Recipe!" );
}
else {
this.EnterOrbit();
}
}
// CELERON
function Celeron() {
};
Celeron.prototype = new Planet('Celeron', -1, -1);
Celeron.prototype.Collide = function() {
alert("Collided with Celeron!");
MapObject.prototype.Collide.call(this);
this.EnterOrbit();
}
// RYZEN
function Ryzen() {
};
Ryzen.prototype = new Planet('Ryzen', -1, -1);
Ryzen.prototype.Collide = function() {
alert("Collided with Ryzen!");
MapObject.prototype.Collide.call(this);
this.EnterOrbit();
}
// XEON
function Xeon() {
};
Xeon.prototype = new Planet('Xeon', -1, -1);
Xeon.prototype.Collide = function() {
alert("Collided with Xeon");
MapObject.prototype.Collide.call(this);
this.EnterOrbit();
}
// BAD MAX
function BadMax () { }
BadMax.prototype = new MapObject("BadMax", 0);
BadMax.prototype.isHidden = true;
BadMax.prototype.Collide = function () {
MapObject.prototype.Collide.call(this);
let eventDecider = Math.random();
// you escape
if (eventDecider < 0.5) {
this.Escape();
}
// you steal
else if (eventDecider < 0.8) {
this.Steal();
}
// your ship is destroyed
else {
this.DestroyShip();
}
//reposition badmax after encounter with OldSpice and delete previous BadMax from the map
gameMap.remove( oldSpice.x, oldSpice.y ); // remove this BadMax from the map
generateBadMax( gameMap ); //add a new badmax to the map
}
BadMax.prototype.Steal = function() {
alert("BadMax has boarded your ship and stolen half your supplies and all your credits!");
oldSpice.supplies /= 2;
oldSpice.credit = 0;
}
BadMax.prototype.DestroyShip = function() {
ctrecipe.GameOver("BadMax and his henchmen blasted your ship!");
}
BadMax.prototype.Escape = function() {
alert("You come across BadMax but successfuly lose him and his henchmen!");
}
// RECIPE
function KokaKolaRecipe() {
}
KokaKolaRecipe.prototype = new MapObject("Recipe", 0);
KokaKolaRecipe.prototype.isHidden = true;
KokaKolaRecipe.prototype.Collide = function() {
MapObject.prototype.Collide.call(this);
oldSpice.recipe = true;
alert("You got the KokaKola recipe! Return to Eniac!");
gameMap.remove(oldSpice.x, oldSpice.y); // remove the recipe from the map because user has obtained it
}
// GAME OF CHANCE VAR
var playGameOfChance;
// SPACE STATION
function SpaceStation ( attachedStations ) {
}
SpaceStation.prototype = new MapObject( "Station", 0 );
SpaceStation.prototype.Collide = function () {
}
function CheckBalance ( price ) {
}
function gameOfChance () {
}
// WINNINGS
function PlayGameOfChance () {
}
// MUSKTESTA
function MuskTesla ( energyQuantity, energyPrice ) {
}
MuskTesla.prototype.MenuPrompt = function () {
}
MuskTesla.prototype.Purchase = function () {
}
// MINI MART
function MiniMart () {
}
MiniMart.prototype.MenuPrompt = function () {
}
MiniMart.prototype.Purchase = function () {
}
// REPAIR DEPOT
function RepairDepot () {
}
RepairDepot.prototype.MenuPrompt = function () {
}
RepairDepot.prototype.Purchase = function () {
}
| 5011ba73551942c06d2c5b2208b0c43245bed155 | [
"JavaScript"
] | 9 | JavaScript | angiemcgraw/Nov21-up | b0dbf76c65750e0a2d7a7f1a31c7021f4e310555 | c9b2407e1dfdad9ac5da474fc5b2f7783f9e2f2b | |
refs/heads/master | <repo_name>xyTianZhao/XiyouLibrary<file_sep>/src/com/tz/xiyoulibrary/activity/bookdetial/presenter/BookDetialPresenter.java
package com.tz.xiyoulibrary.activity.bookdetial.presenter;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.bookdetial.model.BookDetialModel;
import com.tz.xiyoulibrary.activity.bookdetial.model.IBookDetialModel;
import com.tz.xiyoulibrary.activity.bookdetial.view.IBookDetialView;
import com.tz.xiyoulibrary.activity.callback.CallBack;
public class BookDetialPresenter {
private IBookDetialView mBookDetialView;
private IBookDetialModel mBookDetialModel;
public BookDetialPresenter(IBookDetialView view) {
this.mBookDetialView = view;
mBookDetialModel = new BookDetialModel();
}
/**
* 获取书籍信息
*/
public void getBookDetial(RequestQueue queue, String url) {
mBookDetialModel.getBookDetial(queue, url,
new CallBack<BookDetialModel>() {
@Override
public void getModel(BookDetialModel model) {
switch (model.state) {
case IBookDetialModel.LOADING:
mBookDetialView.showLoadingView();
break;
case IBookDetialModel.LOADING_FALUIRE:
mBookDetialView.showLoadFaluireView();
mBookDetialView.showMsg(model.msg);
break;
case IBookDetialModel.NO_DATA:
mBookDetialView.showNoDataView();
break;
case IBookDetialModel.LOADING_SUCCESS:
mBookDetialView
.showBookDetialView(model.bookDetial);
break;
}
}
});
}
/**
* 添加收藏
*/
public void collection(RequestQueue queue, String id) {
mBookDetialModel.collection(queue, id, new CallBack<BookDetialModel>() {
@Override
public void getModel(BookDetialModel model) {
switch (model.state) {
case IBookDetialModel.LOADING:
mBookDetialView.showDialog();
break;
case IBookDetialModel.LOADING_FALUIRE:
case IBookDetialModel.LOADING_SUCCESS:
mBookDetialView.hidenDialog();
mBookDetialView.showMsg(model.msg);
break;
}
}
});
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/search/view/ISearchView.java
package com.tz.xiyoulibrary.activity.search.view;
import java.util.List;
import java.util.Map;
public interface ISearchView {
void showBookListView(List<Map<String, String>> bookList);
void showNoDataView();
}
<file_sep>/src/com/tz/xiyoulibrary/activity/homedetail/view/IHomeDetailView.java
package com.tz.xiyoulibrary.activity.homedetail.view;
import java.util.Map;
public interface IHomeDetailView {
void showLoadingView();
void showMsg(String msg);
void showDetailData(Map<String, String> detailMap);
void showNoDataView();
void showLoadFailView();
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mybroorw/view/MyBorrowAdapter.java
package com.tz.xiyoulibrary.activity.mybroorw.view;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.StringRequest;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.application.Application;
import com.tz.xiyoulibrary.bean.BookBean;
import com.tz.xiyoulibrary.dialog.progressbar.MyProgressBar;
import com.tz.xiyoulibrary.toastview.CustomToast;
import com.tz.xiyoulibrary.utils.Constants;
import com.tz.xiyoulibrary.utils.adapter.CommonAdapter;
import com.tz.xiyoulibrary.utils.adapter.ViewHolder;
@SuppressLint("HandlerLeak")
public class MyBorrowAdapter extends CommonAdapter<BookBean> {
private ImageLoader imageLoader;
private int position;
private MyProgressBar progressBar;
private RequestQueue queue;
public MyBorrowAdapter(Context context, List<BookBean> mDatas,
int itemLayoutId, ImageLoader imageLoader, RequestQueue queue) {
super(context, mDatas, itemLayoutId);
this.imageLoader = imageLoader;
this.queue = queue;
}
@Override
public void convert(ViewHolder helper, final BookBean b) {
helper.setText(R.id.tv_book_title_item_myborrow, b.getTitle());
helper.setText(R.id.tv_book_department_item_myborrow,
"分馆:" + b.getDepartment());
helper.setText(R.id.tv_book_data_item_myborrow, b.getDate());
ImageView bookImg = helper.getView(R.id.iv_book_img_item_myborrow);
String imgUrl = b.getImgUrl();
bookImg.setTag(imgUrl);
if (TextUtils.equals(imgUrl, "")) {
bookImg.setBackgroundResource(R.drawable.img_book_no);
} else if (bookImg.getTag().toString().equals(imgUrl)) {
ImageListener imageListener = ImageLoader.getImageListener(bookImg,
R.drawable.img_book, R.drawable.img_book_no);
imageLoader.get(imgUrl, imageListener, 240, 320);
}
TextView tv = helper.getView(R.id.tv_book_state_item_myborrow);
Button bt = helper.getView(R.id.bt_book_state_item_myborrow);
if (b.getCanRenew()) {
bt.setVisibility(View.VISIBLE);
tv.setVisibility(View.GONE);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
position = mDatas.indexOf(b);
progressBar = new MyProgressBar(mContext);
progressBar.show();
// 续借图书
renewBook();
}
});
} else {
bt.setVisibility(View.GONE);
tv.setVisibility(View.VISIBLE);
tv.setText(b.getState());
}
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (progressBar.isShowing())
progressBar.dismiss();
switch (msg.what) {
case 0x001:// 失败
CustomToast.showToast(mContext, "续借失败", 2000);
break;
case 0x002:// 成功
CustomToast.showToast(mContext, "续借成功", 2000);
mDatas.get(position).setState((String) msg.obj);
notifyDataSetChanged();
break;
}
};
};
/**
* 续借图书
*/
private void renewBook() {
StringRequest renewRequest = new StringRequest(Method.POST,
Constants.GET_BOOK_RENEW, new Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
Message msg = Message.obtain();
msg.what = 0x002;
msg.obj = o.getString("Detail");
handler.sendMessage(msg);
} else {
handler.sendEmptyMessage(0x001);
}
} catch (JSONException e) {
e.printStackTrace();
handler.sendEmptyMessage(0x001);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
handler.sendEmptyMessage(0x001);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
BookBean currBook = mDatas.get(position);
Map<String, String> map = new HashMap<String, String>();
map.put("session", Application.SESSION);
map.put("barcode", currBook.getBarCode());
map.put("department_id", currBook.getDepartment_id());
map.put("library_id", currBook.getLibrary_id());
return map;
}
};
renewRequest.setRetryPolicy(new DefaultRetryPolicy(
Constants.TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(renewRequest);
}
}
<file_sep>/src/com/tz/xiyoulibrary/utils/ConfigFile.java
package com.tz.xiyoulibrary.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
*
* @author tianzhao 配置文件类
*/
public class ConfigFile {
private static SharedPreferences sp;
private static final String CONFIG_FILE_NAME = "XiYou_Library";
private static final String UserName = "username";
private static final String PassWord = "<PASSWORD>";
private static final String IsSavePassWord = "<PASSWORD>";
private static final String IsAutoLogin = "isAutoLogin";
// 消息通知
private static final String SETTING_MESSAGE_NOTIC = "setting_message_notic";
// 网络图片显示
private static final String SETTING_NET = "setting_net";
public static void saveUsername(Context context, String username) {
initSp(context);
sp.edit().putString(UserName, username).commit();
}
public static void savePassword(Context context, String password) {
initSp(context);
sp.edit().putString(PassWord, password).commit();
}
public static String getUsername(Context context) {
initSp(context);
return sp.getString(UserName, "");
}
public static String getPassword(Context context) {
initSp(context);
return sp.getString(PassWord, "");
}
public static void saveIsSavePass(Context context, boolean isSavePass) {
initSp(context);
sp.edit().putBoolean(IsSavePassWord, isSavePass).commit();
}
public static boolean getIsSavePass(Context context) {
initSp(context);
return sp.getBoolean(IsSavePassWord, false);
}
public static void saveIsAutoLogin(Context context, boolean isAutoLogin) {
initSp(context);
sp.edit().putBoolean(IsAutoLogin, isAutoLogin).commit();
}
public static boolean getIsAutoLogin(Context context) {
initSp(context);
return sp.getBoolean(IsAutoLogin, false);
}
public static boolean getMessageNotic(Context context) {
initSp(context);
return sp.getBoolean(SETTING_MESSAGE_NOTIC, true);
}
public static void saveMessageNotic(Context context,
boolean message_notic_status) {
initSp(context);
sp.edit().putBoolean(SETTING_MESSAGE_NOTIC, message_notic_status).commit();
}
public static boolean getNet(Context context) {
initSp(context);
return sp.getBoolean(SETTING_NET, true);
}
public static void saveNet(Context context, boolean net_status) {
initSp(context);
sp.edit().putBoolean(SETTING_NET, net_status).commit();
}
private static void initSp(Context context) {
sp = context.getSharedPreferences(CONFIG_FILE_NAME,
Context.MODE_PRIVATE);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/about/AboutActivity.java
package com.tz.xiyoulibrary.activity.about;
import java.io.File;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.activity.advice.AdviceActivity_;
import com.tz.xiyoulibrary.activity.baseactivity.BaseActivity;
import com.tz.xiyoulibrary.activity.question.QuestionActivity_;
import com.tz.xiyoulibrary.dialog.progressbar.MyProgressBar;
import com.tz.xiyoulibrary.dialog.progressdialog.MyAlertDialog;
import com.tz.xiyoulibrary.toastview.CustomToast;
import com.tz.xiyoulibrary.utils.Constants;
import com.tz.xiyoulibrary.utils.LogUtils;
import com.tz.xiyoulibrary.utils.UpDateUtils;
@SuppressLint("HandlerLeak")
@EActivity(R.layout.activity_about)
public class AboutActivity extends BaseActivity {
@ViewById(R.id.rl_back_actionbar)
RelativeLayout mRelativeLayoutBack;
@ViewById(R.id.tv_title_actionbar)
TextView mTextViewTitle;
@ViewById(R.id.tv_version_about_activity)
TextView mTextViewVersion;
@ViewById(R.id.tv_update_about_activity)
TextView mTextViewUpdate;
@ViewById(R.id.tv_question_about_activity)
TextView mTextViewQuestion;
@ViewById(R.id.tv_back_advice_about_activity)
TextView mTextViewBackAdvice;
@ViewById(R.id.tv_our_web_about_activity)
TextView mTextViewOurWeb;
private MyProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = new MyProgressBar(AboutActivity.this);
}
@AfterViews
public void initWidgetAfter() {
mRelativeLayoutBack.setVisibility(View.VISIBLE);
mTextViewTitle.setText("关于我们");
mTextViewOurWeb.setText(Html.fromHtml("<u>" + "访问我们的主页" + "</u>"));
mTextViewVersion.setText("Version" + Constants.versionName);
}
@Click(R.id.rl_back_actionbar)
public void back() {
finish();
}
@Click(R.id.tv_update_about_activity)
public void update() {
if (!UpDateUtils.isNew) {
showUpdateView();
} else {
progressBar.show();
handler.sendEmptyMessageDelayed(0x004, 2000);
}
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 0x001) {
progressBar.show();
CustomToast.showToast(AboutActivity.this, "开始下载", 2000);
} else if (msg.what == 0x003) {// 下载完成
CustomToast.showToast(AboutActivity.this, "下载完成", 2000);
LogUtils.d("MainActivity", "下载完成");
progressBar.dismiss();
File apkFile = (File) msg.obj;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile),
"application/vnd.android.package-archive");
startActivity(intent);
} else if (msg.what == 0x004) {
progressBar.dismiss();
CustomToast.showToast(AboutActivity.this, "已是最新版本", 2000);
} else {// 正在下载
LogUtils.d("MainActivity : currProgress", msg.what + "%");
progressBar.setCurrProgress(msg.what);
}
};
};
private void showUpdateView() {
MyAlertDialog alertDialog = new MyAlertDialog(AboutActivity.this,
"亲!出新版本了,是否下载?", new MyAlertDialog.MyAlertDialogListener() {
@Override
public void confirm() {
// 下载新文件
UpDateUtils.downLoadApk(handler);
}
});
alertDialog.setCancelable(false);
alertDialog.show();
}
/**
* 常见问题
*/
@Click(R.id.tv_question_about_activity)
public void question() {
startActivity(new Intent(AboutActivity.this, QuestionActivity_.class));
}
/**
* 意见反馈
*/
@Click(R.id.tv_back_advice_about_activity)
public void backAdvice() {
startActivity(new Intent(AboutActivity.this, AdviceActivity_.class));
}
@Click(R.id.tv_our_web_about_activity)
public void uourWeb() {
Uri uri = Uri.parse("http://xiyoumobile.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mycollection/activity/presenter/MyCollectionPresenter.java
package com.tz.xiyoulibrary.activity.mycollection.activity.presenter;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.activity.mycollection.activity.model.IMyCollectionModel;
import com.tz.xiyoulibrary.activity.mycollection.activity.model.MyCollectionModel;
import com.tz.xiyoulibrary.activity.mycollection.activity.view.IMyCollectionView;
public class MyCollectionPresenter {
private IMyCollectionView mMyCollectionView;
private IMyCollectionModel mMyCollectionModel;
public MyCollectionPresenter(IMyCollectionView view) {
this.mMyCollectionView = view;
mMyCollectionModel = new MyCollectionModel();
}
/**
* »ñÈ¡ÊÕ²ØÊé¼®
*/
public void getFavoriteData(RequestQueue queue) {
mMyCollectionModel.getFavoriteData(queue,
new CallBack<MyCollectionModel>() {
@Override
public void getModel(MyCollectionModel model) {
switch (model.status) {
case IMyCollectionModel.LOADING:
mMyCollectionView.showLoadView();
break;
case IMyCollectionModel.LOADING_FALUIRE:
mMyCollectionView.showGetDataFaluire();
mMyCollectionView.showMsg(model.msg);
break;
case IMyCollectionModel.NO_DATA:
mMyCollectionView.showGetDataNoData();
break;
case IMyCollectionModel.LOADING_SUCCESS:
mMyCollectionView
.showFavoriteData(model.favoriteData);
break;
}
}
});
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/homedetail/model/HomeDetailModel.java
package com.tz.xiyoulibrary.activity.homedetail.model;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.tz.xiyoulibrary.activity.callback.CallBack;
public class HomeDetailModel implements IHomeDetailModel{
public int status;
public String message;
// public String detailMsg;
public Map<String, String> detailMap;
@Override
public void getDetailData(RequestQueue queue, String url,
final CallBack<HomeDetailModel> callBack) {
// TODO Auto-generated method stub
status = LOADING;
callBack.getModel(this);
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
System.out.println("response="+response);
getDataByJson(response, callBack);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
status = LOADING_FALUIRE;
message = "加载失败";
callBack.getModel(HomeDetailModel.this);
}
});
queue.add(request);
}
public void getDataByJson(String response,CallBack<HomeDetailModel> callBack){
detailMap = new HashMap<String, String>();
try {
JSONObject obj1 = new JSONObject(response);
if(obj1.getBoolean("Result")){
JSONObject obj2 = obj1.getJSONObject("Detail");
detailMap.put("Title",obj2.getString("Title"));
detailMap.put("Publisher", obj2.getString("Publisher"));
detailMap.put("Date", obj2.getString("Date"));
detailMap.put("Passage", obj2.getString("Passage"));
status = LOADING_SUCCESS;
}else{
status = LOADING_FALUIRE;
message = "获取信息失败";
}
} catch (JSONException e) {
// TODO Auto-generated catch block
status = LOADING_FALUIRE;
message = "获取信息失败";
}
callBack.getModel(HomeDetailModel.this);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mycollection/fragment/BookPagerAdapter.java
package com.tz.xiyoulibrary.activity.mycollection.fragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.android.volley.toolbox.ImageLoader;
/**
* User: shine Date: 2015-03-13 Time: 09:21 Description:
*/
@SuppressWarnings("unchecked")
public class BookPagerAdapter extends FragmentStatePagerAdapter {
private List<Map<String, String>> mBookList;
@SuppressWarnings("rawtypes")
private List<Fragment> mFragments = new ArrayList();
public BookPagerAdapter(FragmentManager fragmentManager,
List<Map<String, String>> bookList,ImageLoader imageLoader) {
super(fragmentManager);
int position = 0;
// 使用迭代器遍历List,
@SuppressWarnings("rawtypes")
Iterator iterator = bookList.iterator();
while (iterator.hasNext()) {
position++;
Map<String, String> book = (Map<String, String>) iterator.next();
book.put("position", position + "");
// 实例化相应的Fragment并添加到List中
mFragments.add(MyBorrowFragment.getInstance(book,imageLoader));
}
mBookList = bookList;
}
public int getCount() {
return mFragments.size();
}
@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
public List<Map<String, String>> getCardList() {
return mBookList;
}
public List<Fragment> getFragments() {
return mFragments;
}
public void setDatas(List<Map<String, String>> bookList) {
this.mBookList = bookList;
notifyDataSetChanged();
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/search/view/SearchAdapter.java
package com.tz.xiyoulibrary.activity.search.view;
import java.util.List;
import java.util.Map;
import android.content.Context;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.utils.adapter.CommonAdapter;
import com.tz.xiyoulibrary.utils.adapter.ViewHolder;
public class SearchAdapter extends CommonAdapter<Map<String,String>>{
public SearchAdapter(Context context, List<Map<String, String>> mDatas,
int itemLayoutId) {
super(context, mDatas, itemLayoutId);
// TODO Auto-generated constructor stub
}
@Override
public void convert(ViewHolder helper, Map<String, String> map) {
// TODO Auto-generated method stub
helper.setText(R.id.book_title,map.get("Title").toString());
helper.setText(R.id.book_author, map.get("Author").toString());
helper.setText(R.id.book_id, map.get("ID").toString());
}
}
<file_sep>/src/com/tz/xiyoulibrary/bean/BookBean.java
package com.tz.xiyoulibrary.bean;
import java.io.Serializable;
/**
*
* @author tianzhao 图书馆图书信息
*/
public class BookBean implements Serializable {
private static final long serialVersionUID = -5223987826917760780L;
private String id;// 图书馆内控制号
private String ISBN;//标准号
private String title;// 标题
private String secondTitle;// 副标题
private String pub;// 出版社
private String author;// 责任者,作者
private String sort;// 图书馆索书号
private String subject; // 主题
private String total;// 图书馆藏书数量
private String avaliable;// 可借阅数量
private String barCode;// 条形码
private String department;// 所在分馆
private String state;// 当前状态
private String date;// 应还日期
private boolean canRenew;// 是否可续借
private String department_id;// 书库ID号,用于续借
private String library_id;// 分馆ID号,用于续借
private String imgUrl;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public boolean getCanRenew() {
return canRenew;
}
public void setCanRenew(boolean canRenew) {
this.canRenew = canRenew;
}
public String getDepartment_id() {
return department_id;
}
public void setDepartment_id(String department_id) {
this.department_id = department_id;
}
public String getLibrary_id() {
return library_id;
}
public void setLibrary_id(String library_id) {
this.library_id = library_id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getSecondTitle() {
return secondTitle;
}
public void setSecondTitle(String secondTitle) {
this.secondTitle = secondTitle;
}
public String getPub() {
return pub;
}
public void setPub(String pub) {
this.pub = pub;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getAvaliable() {
return avaliable;
}
public void setAvaliable(String avaliable) {
this.avaliable = avaliable;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mycollection/activity/view/IMyCollectionView.java
package com.tz.xiyoulibrary.activity.mycollection.activity.view;
import java.util.List;
import java.util.Map;
public interface IMyCollectionView {
/**
* 显示收藏数据/获取数据成功
*
* @param favoriteData
*/
void showFavoriteData(List<Map<String, String>> favoriteData);
/**
* 获取数据失败
*/
void showGetDataFaluire();
/**
* 当前没有收藏
*/
void showGetDataNoData();
/**
* 显示获取视图
*/
void showLoadView();
void showMsg(String msg);
}
<file_sep>/src/com/tz/xiyoulibrary/activity/homedetail/view/HomeDetailActivity.java
package com.tz.xiyoulibrary.activity.homedetail.view;
import java.util.Map;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.activity.baseactivity.BaseActivity;
import com.tz.xiyoulibrary.activity.homedetail.presenter.HomeDetailPresenter;
import com.tz.xiyoulibrary.titanicview.Titanic;
import com.tz.xiyoulibrary.titanicview.TitanicTextView;
import com.tz.xiyoulibrary.titanicview.Typefaces;
import com.tz.xiyoulibrary.toastview.CustomToast;
import com.tz.xiyoulibrary.utils.Constants;
import com.tz.xiyoulibrary.utils.LogUtils;
@SuppressLint("HandlerLeak")
@EActivity(R.layout.home_list_detail)
public class HomeDetailActivity extends BaseActivity implements IHomeDetailView {
@ViewById(R.id.rl_back_actionbar)
RelativeLayout mRelativeLayoutBack;
@ViewById(R.id.tv_title_actionbar)
TextView mTextViewTitle;
Titanic mTitanic;
@ViewById(R.id.loading_text)
TitanicTextView mTitanicTextView;
@ViewById(R.id.rl_loading)
RelativeLayout mRelativeLayoutLoading;
@ViewById(R.id.rl_load_faluire)
RelativeLayout mRelativeLayoutLoadFaluire;
@ViewById(R.id.rl_load_no_data)
RelativeLayout mRelativeLayoutLoadNoData;
@ViewById(R.id.tv_load_no_data_tip)
TextView mTextViewTip;
@ViewById(R.id.layout_homedetail)
RelativeLayout layout_homedetail;
@ViewById(R.id.homedetail)
WebView homeDetailWebView;
@ViewById(R.id.iv_home_moreoption)
ImageView home_MoreOption;
@ViewById(R.id.publisher)
TextView homedetail_published;
@ViewById(R.id.publish_date)
TextView homedetail_publish_date;
@ViewById(R.id.homeTitle)
TextView homedetail_title;
@ViewById(R.id.layout_publisher)
LinearLayout layout_publisher;
@ViewById(R.id.layout_publish_date)
LinearLayout layout_publish_date;
private String url;
private HomeDetailPresenter mPresenter;
private RequestQueue queue;
private Map<String, String> detailMap;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue = Volley.newRequestQueue(HomeDetailActivity.this);
url = Constants.GET_NEWS_DETAIL
+ getIntent().getStringExtra("laterUrl");
mPresenter = new HomeDetailPresenter(this);
LogUtils.d("HomeDetailActivity : ", "传过来的url=" + url);
}
@AfterViews
public void init() {
homeDetailWebView.setVerticalScrollBarEnabled(false); // 垂直不显示 ,去掉垂直滚动条
mTitanicTextView
.setTypeface(Typefaces.get(this, "Satisfy-Regular.ttf"));
mTitanic = new Titanic();
mRelativeLayoutBack.setVisibility(View.VISIBLE);
mTextViewTitle.setText("详情");
mPresenter.getHomeDetailData(queue, url);
}
@Click(R.id.iv_home_moreoption)
public void moreOption() {
// 弹出更多选项
}
@Override
public void showLoadingView() {
mRelativeLayoutLoading.setVisibility(View.VISIBLE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mTitanic.start(mTitanicTextView);
}
@Override
public void showMsg(String msg) {
CustomToast.showToast(this, msg, 2000);
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
layout_publisher.setVisibility(View.VISIBLE);
layout_publish_date.setVisibility(View.VISIBLE);
homedetail_published.setText(detailMap.get("Publisher"));
homedetail_publish_date.setText(detailMap.get("Date"));
};
};
@Override
public void showDetailData(Map<String, String> detailMap) {
// 关闭加载动画
mTitanic.cancel();
// 隐藏加载视图
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
this.detailMap = detailMap;
homedetail_title.setText(detailMap.get("Title"));
System.out.println("title = " + detailMap.get("Title"));
System.out.println("passage = " + detailMap.get("Passage"));
homeDetailWebView.loadDataWithBaseURL(null, detailMap.get("Passage"),
"text/html", "utf-8", null);
handler.sendEmptyMessageDelayed(0, 1000);
}
@Override
public void showNoDataView() {
mTitanic.cancel();
mRelativeLayoutLoadNoData.setVisibility(View.VISIBLE);
mTextViewTip.setText("哦啊~当前没有排行信息!");
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mRelativeLayoutLoading.setVisibility(View.GONE);
}
@Override
public void showLoadFailView() {
mTitanic.cancel();
mRelativeLayoutLoadFaluire.setVisibility(View.VISIBLE);
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
}
@Click(R.id.rl_back_actionbar)
public void back() {
finish();
}
@Click(R.id.rl_load_faluire)
public void resetData() {
mPresenter.getHomeDetailData(queue, url);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/bookdetial/view/ReferAdapter.java
package com.tz.xiyoulibrary.activity.bookdetial.view;
import java.util.List;
import java.util.Map;
import android.content.Context;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.utils.adapter.CommonAdapter;
import com.tz.xiyoulibrary.utils.adapter.ViewHolder;
public class ReferAdapter extends CommonAdapter<Map<String, String>> {
public ReferAdapter(Context context, List<Map<String, String>> mDatas,
int itemLayoutId) {
super(context, mDatas, itemLayoutId);
}
@Override
public void convert(ViewHolder helper, Map<String, String> map) {
helper.setText(R.id.tv_title_item_refer, "¡¶"+map.get("Title")+"¡·");
helper.setText(R.id.tv_author_item_refer, map.get("Author"));
helper.setText(R.id.tv_id_item_refer, map.get("ID"));
}
}
<file_sep>/src/com/tz/xiyoulibrary/bubblesbackview/BubbleBackView.java
package com.tz.xiyoulibrary.bubblesbackview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import java.util.Random;
import com.tz.xiyoulibrary.R;
/**
* Created by tianzhao on 2015/10/25. Date 21:38
*/
public class BubbleBackView extends View {
private int circleSum;// 圆的数量
private int circleRadio;// 圆的半径
private int circleColor;// 圆的颜色
private int backColor;// 背景颜色
private Paint backPaint;// 背景画笔
private Paint circlePaint;// 圆的画笔
private Circle[] circles;
private int[] direction = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
private Random random;
private float width;
private float height;
private int[] location = new int[2];
private MyThread mMyThread;
private boolean running = true;
public BubbleBackView(Context context) {
super(context);
backPaint = new Paint();
init();
}
public BubbleBackView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs,
R.styleable.BubbleBackView);
circleSum = ta.getInteger(R.styleable.BubbleBackView_circleSum, 15);
circleColor = ta.getColor(R.styleable.BubbleBackView_circleColor,
Color.parseColor("#11ffffff"));
backColor = ta.getColor(R.styleable.BubbleBackView_backColor,
getResources().getColor(R.color.theme_color));
circleRadio = ta.getInteger(R.styleable.BubbleBackView_circleRadio, 15);
ta.recycle();
init();
}
/**
* 初始化画笔
*/
private void init() {
backPaint = new Paint();
backPaint.setColor(backColor);
circlePaint = new Paint();
circlePaint.setColor(circleColor);
}
/**
* 比onDraw先执行
* <p/>
* 一个MeasureSpec封装了父布局传递给子布局的布局要求,每个MeasureSpec代表了一组宽度和高度的要求。
* 一个MeasureSpec由大小和模式组成
* 它有三种模式:UNSPECIFIED(未指定),父元素部队自元素施加任何束缚,子元素可以得到任意想要的大小;
* EXACTLY(完全),父元素决定自元素的确切大小,子元素将被限定在给定的边界里而忽略它本身大小;
* AT_MOST(至多),子元素至多达到指定大小的值。
* <p/>
* 它常用的三个函数: 1.static int getMode(int
* measureSpec):根据提供的测量值(格式)提取模式(上述三个模式之一) 2.static int getSize(int
* measureSpec):根据提供的测量值(格式)提取大小值(这个大小也就是我们通常所说的大小) 3.static int
* makeMeasureSpec(int size,int mode):根据提供的大小值和模式创建一个测量值(格式)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获取控件宽度
width = getMeasuredWidth();
// 获取控件高度
height = getMeasuredHeight();
// 获取控件相对于父控件的位置坐标
this.getLocationInWindow(location);
// 初始化圆
initCircle();
}
/**
* 初始化圆
*/
private void initCircle() {
circles = new Circle[circleSum];
random = new Random();
for (int i = 0; i < circleSum; i++) {
int d = random.nextInt(direction.length);
int x = random.nextInt((int) width);
int y = random.nextInt((int) height);
int r = random.nextInt(circleRadio) + circleRadio;
circles[i] = new Circle(x, y, d, dpTopx(r));
}
}
@Override
protected void onDraw(Canvas canvas) {
// 绘制背景
canvas.drawRect(0, 0, location[0] + width, location[1] + height,
backPaint);
// 遍历绘制每一个圆
for (Circle c : circles) {
canvas.drawCircle(c.getX(), c.getY(), c.getR(), circlePaint);
}
if (mMyThread == null) {
mMyThread = new MyThread();
mMyThread.start();
}
}
/**
* 不在窗口显示的时候停止线程
*/
@Override
protected void onDetachedFromWindow() {
running = false;
super.onDetachedFromWindow();
}
class MyThread extends Thread {
@Override
public void run() {
while (running) {
for (int i = 0; i < circles.length; i++) {
Circle c = circles[i];
changeDirection(c);
if (c.getY() < 0) {// 超出上边
int d;
while (true) {
d = random.nextInt(direction.length);
if (d % 2 != 0)
break;
}
circles[i].setDirection(d);
} else if (c.getY() > height) {// 超出下边
int d;
while (true) {
d = random.nextInt(direction.length);
if (d % 2 != 1)
break;
}
circles[i].setDirection(d);
} else if (c.getX() < 0) {// 超出左边
int d;
while (true) {
d = random.nextInt(direction.length);
if (d == 6 || d == 10 || d == 3 || d == 7
|| d == 11)
break;
}
circles[i].setDirection(d);
} else if (c.getX() > width) {// 超出右边
int d;
while (true) {
d = random.nextInt(direction.length);
if (d == 4 || d == 8 || d == 2 || d == 5 || d == 9)
break;
}
circles[i].setDirection(d);
}
}
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
postInvalidate();
}
}
private void changeDirection(Circle c) {
float dx = 0.3f;
int d;
try {
d = c.getDirection();
} catch (Exception e) {
d = 0;
}
switch (d) {
case 0:// 上
c.setY(c.getY() - dx);
break;
case 1:// 下
c.setY(c.getY() + dx);
break;
case 2:// 左
c.setX(c.getX() - dx);
break;
case 3:// 右
c.setX(c.getX() + dx);
break;
case 4:// 左上
c.setX(c.getX() - dx);
c.setY(c.getY() - dx);
break;
case 5:// 左下
c.setX(c.getX() - dx);
c.setY(c.getY() + dx);
break;
case 6:// 右上
c.setX(c.getX() + dx);
c.setY(c.getY() - dx);
break;
case 7:// 右下
c.setX(c.getX() + dx);
c.setY(c.getY() + dx);
break;
case 8:// 左上
c.setX(c.getX() - dx);
c.setY(c.getY() - dx * 2);
break;
case 9:// 左下
c.setX(c.getX() - dx * 2);
c.setY(c.getY() + dx);
break;
case 10:// 右上
c.setX(c.getX() + dx);
c.setY(c.getY() - dx * 2);
break;
case 11:// 右下
c.setX(c.getX() + dx);
c.setY(c.getY() + dx * 2);
break;
}
}
}
class Circle {
private float x;
private float y;
private float r;
private int direction = 0;
public Circle(float x, float y, int d) {
this.x = x;
this.y = y;
this.direction = d;
}
public Circle(float x, float y, int d, int r) {
this.x = x;
this.y = y;
this.r = r;
this.direction = d;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public void setY(float y) {
this.y = y;
}
public float getY() {
return y;
}
public void setDirection(int direction) {
this.direction = direction;
}
public int getDirection() {
return direction;
}
public float getR() {
return r;
}
public void setR(float r) {
this.r = r;
}
}
private int dpTopx(int dp) {
float scale = getResources().getDisplayMetrics().density;
return (int) (dp * scale + 0.5f);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mybroorw/view/IMyborrowView.java
package com.tz.xiyoulibrary.activity.mybroorw.view;
import java.util.List;
import com.tz.xiyoulibrary.bean.BookBean;
public interface IMyborrowView {
void showLoadingView();
void showBorrowView(List<BookBean> borrowData);
void showLoadFaluireView();
void showNoDataView();
void showMsg(String msg);
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mybroorw/presenter/MyBorrowPresenter.java
package com.tz.xiyoulibrary.activity.mybroorw.presenter;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.activity.mybroorw.model.IMyBorrowModel;
import com.tz.xiyoulibrary.activity.mybroorw.model.MyBorrowModel;
import com.tz.xiyoulibrary.activity.mybroorw.view.IMyborrowView;
public class MyBorrowPresenter {
private IMyborrowView mMyborrowView;
private IMyBorrowModel mMyBorrowModel;
public MyBorrowPresenter(IMyborrowView view) {
this.mMyborrowView = view;
mMyBorrowModel = new MyBorrowModel();
}
public void getBorrowData(RequestQueue queue) {
mMyBorrowModel.getBorrowData(queue, new CallBack<MyBorrowModel>() {
@Override
public void getModel(MyBorrowModel model) {
switch (model.status) {
case IMyBorrowModel.LOADING:
mMyborrowView.showLoadingView();
break;
case IMyBorrowModel.LOADING_FALUIRE:
mMyborrowView.showLoadFaluireView();
mMyborrowView.showMsg(model.msg);
break;
case IMyBorrowModel.NO_DATA:
mMyborrowView.showNoDataView();
break;
case IMyBorrowModel.LOADING_SUCCESS:
mMyborrowView.showBorrowView(model.borrowData);
break;
}
}
});
}
}
<file_sep>/src/com/tz/xiyoulibrary/utils/Constants.java
package com.tz.xiyoulibrary.utils;
import android.os.Environment;
/**
*
* @author tianzhao 全局常量
*/
public class Constants {
// 请求网络超时时间
public static final int TIMEOUT_MS = 10000;
//当前版本号
public static int versionCode;
//当前版本名
public static String versionName;
//2G、3G、4G下是否下载图片
public static boolean isLoadImg;
//当前网络类型
public static int network_type = 0x123;
// 图片缓存路径
public static final String IMG_CACHE_DIR_PATH = Environment
.getExternalStorageDirectory().getPath() + "/xiyouLibrary";
// 服务器地址
private static final String ROOT_URL = "http://api.xiyoumobile.com/xiyoulibv2/";
/***************************** 用户 ********************************/
/**
* 登录
*/
public static final String GET_USER_LOGIN = ROOT_URL + "user/login";
/**
* 用户信息
*/
public static final String GET_USER_INFO = ROOT_URL + "user/info";
/**
* 修改密码
*/
public static final String GET_USER_MODIFY_PASSWORD = ROOT_URL + "user/modifyPassword";
/***************************** 图书 ********************************/
/**
* 用户借阅历史
*/
public static final String GET_BOOK_HISTORY = ROOT_URL + "user/history";
/**
* 用户当前借阅情况
*/
public static final String GET_BOOK_RENT = ROOT_URL + "user/rent";
/**
* 图书续借
*/
public static final String GET_BOOK_RENEW = ROOT_URL + "user/renew";
/**
* 图书收藏
*/
public static final String GET_BOOK_FAVORITE = ROOT_URL + "user/favorite";
/**
* 图书收藏(有图片)
*/
public static final String GET_BOOK_FAVORITE_IMG = ROOT_URL
+ "user/favoriteWithImg";
/**
* 添加图书收藏
*/
public static final String GET_BOOK_ADD_FAVORITE = ROOT_URL + "user/addFav";
/**
* 删除图书收藏
*/
public static final String GET_BOOK_DELETE_FAVORITE = ROOT_URL
+ "user/delFav";
/**
* 图书检索
*/
public static final String GET_BOOK_SEARCH = ROOT_URL + "book/search";
/**
* 图书详情by--barcode
* eg:http://api.xiyoumobile.com/xiyoulibv2/book/detail/Barcode/03277606
*/
public static final String GET_BOOK_DETAIL_BY_BARCODE = ROOT_URL
+ "book/detail/Barcode/";
/**
* 图书详情by--id
* eg:http://api.xiyoumobile.com/xiyoulibv2/book/detail/id/0100000015
*/
public static final String GET_BOOK_DETAIL_BY_ID = ROOT_URL
+ "book/detail/id/";
/**
* 图书排行榜
*/
public static final String GET_BOOK_RANK = ROOT_URL + "book/rank";
/***************************** 新闻、公告 ********************************/
/**
* 公告、新闻列表 参数1:type:news or announce 参数2:page:1、2、3......
* 新闻eg:http://api.xiyoumobile.com/xiyoulibv2/news/getList/news/1
* 公告eg:http://api.xiyoumobile.com/xiyoulibv2/news/getList/announce/1
*/
public static final String GET_NEWS_LIST = ROOT_URL + "news/getList/";
/**
* 公告、新闻详情 参数1:type:news or announce 参数2:format:text or html 参数3:id
* 新闻eg:http://api.xiyoumobile.com/xiyoulibv2/news/getDetail/news/text/132
* 公告eg
* :http://api.xiyoumobile.com/xiyoulibv2/news/getDetail/announce/html/200
*/
public static final String GET_NEWS_DETAIL = ROOT_URL + "news/getDetail/";
}
<file_sep>/src/com/tz/xiyoulibrary/activity/bookdetial/model/IBookDetialModel.java
package com.tz.xiyoulibrary.activity.bookdetial.model;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
public interface IBookDetialModel {
static final int LOADING_SUCCESS = 0;
static final int LOADING_FALUIRE = 1;
static final int NO_DATA = 2;
static final int LOADING = 3;
void getBookDetial(RequestQueue queue,String url, CallBack<BookDetialModel> callBack);
void collection(RequestQueue queue,String id,CallBack<BookDetialModel> callBack);
}
<file_sep>/src/com/tz/xiyoulibrary/dialog/progressbar/MyProgressBar.java
package com.tz.xiyoulibrary.dialog.progressbar;
import com.tz.xiyoulibrary.R;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
public class MyProgressBar extends Dialog {
private TextView textView;
public MyProgressBar(Context context) {
super(context, R.style.MyDialog);
setCancelable(false);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressbar);
textView = (TextView) findViewById(R.id.tv_progressbar2_msg);
}
public void setCurrProgress(int curr) {
textView.setText(curr + "%");
}
}
<file_sep>/src/com/tz/xiyoulibrary/application/Application.java
package com.tz.xiyoulibrary.application;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.view.View;
import android.widget.ImageView;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.avos.avoscloud.AVOSCloud;
import com.baidu.batsdk.BatSDK;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.activity.event.LoginSuccessEvent;
import com.tz.xiyoulibrary.bean.UserBean;
import com.tz.xiyoulibrary.utils.ConfigFile;
import com.tz.xiyoulibrary.utils.Constants;
import com.tz.xiyoulibrary.utils.LogUtils;
import com.tz.xiyoulibrary.utils.UpDateUtils;
import com.ypy.eventbus.EventBus;
public class Application extends android.app.Application {
// 百度统计appkey
private static final String BAIDU_APP_KEY = "<KEY>";
public static final String BAIDU_REPORTID = "af8750724a";
// LeanCloud
private static final String LEANCLOUD_APP_ID = "9cgrBU19DR43tPm4N47koSDi";
private static final String LEANCLOUD_APP_KEY = "<KEY>";
public static String SESSION = "";
public static String USERNAME = "";
public static UserBean user;
public static String HOME_RESPONSE = "";
public static List<Map<String, Object>> HOME_NOTICE_LIST;
public static List<Map<String, Object>> HOME_NEWS_LIST;
public static List<View> homeAdViews;
private int[] homeAdViewsId = { R.drawable.home_image1,
R.drawable.home_image2, R.drawable.home_image3 };
public static List<View> settingAdViews;
private int[] settingAdViewsId = { R.drawable.h1, R.drawable.h3,
R.drawable.h5 };
private RequestQueue queue;
@Override
public void onCreate() {
super.onCreate();
queue = Volley.newRequestQueue(this);
/**
* 初始化配置信息
*/
initConfig();
/**
* 获取版本信息
*/
initVersion();
/**
* 初始化轮播图片的数据
*/
initAdViews();
/**
* 初始化百度统计
*/
BatSDK.init(this, BAIDU_APP_KEY);
/**
* 初始化LeanCloud统计
*/
AVOSCloud.initialize(this, LEANCLOUD_APP_ID, LEANCLOUD_APP_KEY);
AVOSCloud.setLastModifyEnabled(true);
AVOSCloud.setDebugLogEnabled(true);
/**
* 检查更新
*/
UpDateUtils.checkUpdate();
/**
* 自动登录
*/
autoLogin();
}
/**
* 自动登录
*/
private void autoLogin() {
if (!ConfigFile.getIsAutoLogin(this)
|| ConfigFile.getPassword(this).equals(""))
return;
final String username = ConfigFile.getUsername(this);
final String password = ConfigFile.getPassword(this);
StringRequest request = new StringRequest(Method.POST,
Constants.GET_USER_LOGIN, new Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.d("LoginResponse:", response);
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
SESSION = o.getString("Detail");
USERNAME = username;
getUserInfo();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", <PASSWORD>);
return map;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(Constants.TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
public void getUserInfo() {
StringRequest request = new StringRequest(Method.POST,
Constants.GET_USER_INFO, new Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.d("LoginResponse:", response);
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
JSONObject info = o.getJSONObject("Detail");
UserBean user = new UserBean();
user.setId(info.getString("ID"));
user.setName(info.getString("Name"));
user.setFromData(info.getString("From"));
user.setToData(info.getString("To"));
user.setReaderType(info.getString("ReaderType"));
user.setDepartment(info.getString("Department"));
user.setDebt(info.get("Debt") + "");
Application.user = user;
EventBus.getDefault().post(
new LoginSuccessEvent());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("session", SESSION);
return map;
}
};
queue.add(request);
}
private void initConfig() {
/**
* 初始化配置信息
*/
Constants.isLoadImg = ConfigFile.getNet(this);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null)
Constants.network_type = ni.getType();
}
/**
* 获取版本信息
*/
private void initVersion() {
try {
PackageManager pm = getPackageManager();
PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
Constants.versionCode = pi.versionCode;
Constants.versionName = pi.versionName;
LogUtils.d("Version", "versionCode : " + Constants.versionCode
+ " versionName : " + Constants.versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
/**
* 初始化轮播图片的数据
*/
public void initAdViews() {
// 初始化首页图片数据
homeAdViews = new ArrayList<View>();
for (int i = 0; i < homeAdViewsId.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(homeAdViewsId[i]);
homeAdViews.add(imageView);
}
// 初始化设置图片数据
settingAdViews = new ArrayList<View>();
for (int i = 0; i < settingAdViewsId.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(settingAdViewsId[i]);
settingAdViews.add(imageView);
}
}
}
<file_sep>/src/com/tz/xiyoulibrary/fragment/home/model/HomeModel.java
package com.tz.xiyoulibrary.fragment.home.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.application.Application;
import com.tz.xiyoulibrary.utils.Constants;
public class HomeModel implements IHomeModel{
public int status;
public String message;
String partUrl = Constants.GET_NEWS_LIST;
String url;
public Map<String,Object> map = new HashMap<String, Object>();
public List<Map<String,Object>> list;
// 网络请求
@Override
public void getHomeData(RequestQueue queue,final int CurrentPage ,final int whichTag,
final CallBack<HomeModel> callBack) {
// TODO Auto-generated method stub
status = IHomeModel.LOADING;
callBack.getModel(this);
if(whichTag == 0)
url = partUrl + "announce/"+CurrentPage;
else
url = partUrl + "news/"+CurrentPage;
System.out.println("当前url="+url);
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response);
getDataByJson(response,callBack,whichTag,LOADING_SUCCESS);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
status = LOADING_FALUIRE;
message = "网络异常";
callBack.getModel(HomeModel.this);
}
});
request.setRetryPolicy(new DefaultRetryPolicy(Constants.TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
//解析数据
protected void getDataByJson(String response,CallBack<HomeModel> callBack,int whichTag,int what) {
list = new ArrayList<Map<String,Object>>();
try {
JSONObject obj1 = new JSONObject(response);
if(obj1.getBoolean("Result")){
// 用于判断是否需要再请求
Application.HOME_RESPONSE = response;
JSONObject obj2 = obj1.getJSONObject("Detail");
map.put("CurrentPage", obj2.getInt("CurrentPage"));
map.put("Pages", obj2.get("Pages"));
map.put("Amount", obj2.get("Amount"));
JSONArray arr = obj2.getJSONArray("Data");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj3 = arr.getJSONObject(i);
Map<String, Object> map0 = new HashMap<String, Object>();
map0.put("ID", obj3.getInt("ID"));
map0.put("Title", obj3.getString("Title"));
map0.put("Date", obj3.getString("Date"));
list.add(map0);
}
map.put("Detail", list);
status = what;
if(whichTag == 0){
System.out.println("whichTag = 0 ");
Application.HOME_NOTICE_LIST = list;
}else{
System.out.println("whichTag = 1");
Application.HOME_NEWS_LIST = list;
}
}else{
status = REFER_FALUIRE;
message = "获取信息失败";
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status = REFER_FALUIRE;
message = "获取信息失败";
}
callBack.getModel(HomeModel.this);
}
// 刷新数据
@Override
public void refershHomeData(RequestQueue queue, int CurrentPage,final int whichTag,final int what,
final CallBack<HomeModel> callBack) {
if(whichTag == 0)
url = partUrl + "announce/"+CurrentPage;
else
url = partUrl + "news/"+CurrentPage;
System.out.println("刷新的url="+url);
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response);
getDataByJson(response,callBack,whichTag,what);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
status = REFER_FALUIRE;
message = "网络请求错误";
callBack.getModel(HomeModel.this);
}
});
queue.add(request);
}
// @Override
// public int getItemId(int position) {
// // TODO Auto-generated method stub
// System.out.println("getItemId = "+(Integer) list.get(position).get("ID"));
// return (Integer) list.get(position).get("ID");
// }
}
<file_sep>/src/com/tz/xiyoulibrary/activity/search/presenter/SearchPresenter.java
package com.tz.xiyoulibrary.activity.search.presenter;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.activity.search.model.ISearchModel;
import com.tz.xiyoulibrary.activity.search.model.SearchModel;
import com.tz.xiyoulibrary.activity.search.view.ISearchView;
public class SearchPresenter {
public ISearchModel searchModel;
public ISearchView searchView;
public CallBack<SearchModel> callBack;
public SearchPresenter(ISearchView view){
this.searchView = view;
searchModel = new SearchModel();
callBack = new CallBack<SearchModel>() {
@Override
public void getModel(SearchModel model) {
// TODO Auto-generated method stub
switch (model.status) {
case ISearchModel.SEARCH_FAILURE:
// 不再显示
System.out.println("failure");
break;
case ISearchModel.SEARCH_NO_DATA:
System.out.println("没有数据");
searchView.showNoDataView();
break;
case ISearchModel.SEARCH_SUCCESS:
System.out.println("进入success");
searchView.showBookListView(model.contentList);
System.out.println("list="+model.contentList);
break;
}
}
};
}
public void getSearchList(RequestQueue queue,String keyword){
searchModel.SearchQuery(queue,keyword , callBack);
}
public String getItemId(int position){
return searchModel.getId(position);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/mybroorw/view/MyBorrowActivity.java
package com.tz.xiyoulibrary.activity.mybroorw.view;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.activity.baseactivity.BaseActivity;
import com.tz.xiyoulibrary.activity.bookdetial.view.BookDetialActivity_;
import com.tz.xiyoulibrary.activity.mybroorw.presenter.MyBorrowPresenter;
import com.tz.xiyoulibrary.bean.BookBean;
import com.tz.xiyoulibrary.titanicview.Titanic;
import com.tz.xiyoulibrary.titanicview.TitanicTextView;
import com.tz.xiyoulibrary.titanicview.Typefaces;
import com.tz.xiyoulibrary.toastview.CustomToast;
import com.tz.xiyoulibrary.utils.BitmapCache;
import com.tz.xiyoulibrary.utils.Constants;
/**
*
* @author Administrator 我的借阅
*/
@EActivity(R.layout.activity_myborrow)
public class MyBorrowActivity extends BaseActivity implements IMyborrowView {
@ViewById(R.id.rl_back_actionbar)
RelativeLayout mRelativeLayoutBack;
@ViewById(R.id.tv_title_actionbar)
TextView mTextViewTitle;
@ViewById(R.id.lv_borrow_activity_myborrow)
ListView mListViewBorrow;
private MyBorrowAdapter mMyBorrowAdapter;
private RequestQueue queue;
private ImageLoader imageLoader;
private MyBorrowPresenter mPresenter;
private Titanic mTitanic;
@ViewById(R.id.loading_text)
TitanicTextView mTitanicTextView;
@ViewById(R.id.rl_loading)
RelativeLayout mRelativeLayoutLoading;
@ViewById(R.id.rl_load_faluire)
RelativeLayout mRelativeLayoutLoadFaluire;
@ViewById(R.id.rl_load_no_data)
RelativeLayout mRelativeLayoutLoadNoData;
@ViewById(R.id.tv_load_no_data_tip)
TextView mTextViewTip;
private List<BookBean> borrowData;
private int borrow = 0;// 已借图书数量
private int canBorrow = 0;// 剩余可借数量
private int renewBorrow = 0;// 续借图书数量
private int exceedBorrow = 0;// 超期图书数量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPresenter = new MyBorrowPresenter(this);
queue = Volley.newRequestQueue(MyBorrowActivity.this);
imageLoader = new ImageLoader(queue, new BitmapCache());
}
@AfterViews
public void initWidgetAfter() {
mTitanicTextView
.setTypeface(Typefaces.get(this, "Satisfy-Regular.ttf"));
mTitanic = new Titanic();
mRelativeLayoutBack.setVisibility(View.VISIBLE);
mTextViewTitle.setText("我的借阅");
// 获取借阅数据
getBorrowData();
}
/**
* 获取借阅数据
*/
private void getBorrowData() {
mPresenter.getBorrowData(queue);
}
@Click(R.id.rl_back_actionbar)
public void back() {
finish();
}
@ItemClick(R.id.lv_borrow_activity_myborrow)
public void pushBookDetial(int position) {
if (position == 0)
return;
Intent intent = new Intent(MyBorrowActivity.this,
BookDetialActivity_.class);
intent.putExtra("url", Constants.GET_BOOK_DETAIL_BY_BARCODE
+ borrowData.get(position - 1).getBarCode());
startActivity(intent);
}
@Click(R.id.rl_load_faluire)
public void resetLoad() {
// 重新加载
getBorrowData();
}
@Override
public void showLoadingView() {
mRelativeLayoutLoading.setVisibility(View.VISIBLE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mTitanic.start(mTitanicTextView);
}
@Override
public void showBorrowView(List<BookBean> borrowData) {
// 关闭加载动画
mTitanic.cancel();
// 隐藏加载视图
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
this.borrowData = borrowData;
// 初始化借阅数量
initBorrowCount();
LayoutInflater inflater = LayoutInflater.from(MyBorrowActivity.this);
// 添加头布局
LinearLayout head = (LinearLayout) inflater.inflate(
R.layout.activity_myborrow_head, null);
TextView tv_borrow = (TextView) head
.findViewById(R.id.tv_borrow_book_activity_my_borrow);
tv_borrow.setText("已借图书: " + borrow + "本");
TextView tv_can_borrow = (TextView) head
.findViewById(R.id.tv_can_borrow_book_activity_my_borrow);
tv_can_borrow.setText("剩余可借: " + canBorrow + "本");
TextView tv_renew_borrow = (TextView) head
.findViewById(R.id.tv_renew_book_activity_my_borrow);
tv_renew_borrow.setText("续借图书: " + renewBorrow + "本");
TextView tv_exceed_borrow = (TextView) head
.findViewById(R.id.tv_exceed_book_activity_my_borrow);
tv_exceed_borrow.setText("超期图书: " + exceedBorrow + "本");
mListViewBorrow.addHeaderView(head);
mMyBorrowAdapter = new MyBorrowAdapter(MyBorrowActivity.this,
this.borrowData, R.layout.item_activity_myborrow, imageLoader,queue);
mListViewBorrow.setAdapter(mMyBorrowAdapter);
}
private void initBorrowCount() {
borrow = borrowData.size();
canBorrow = 15 - borrow;
for (BookBean b : borrowData) {
if (b.getState().equals("本馆续借")) {
renewBorrow++;
} else if (b.getState().equals("过期暂停")) {
exceedBorrow++;
}
}
}
@Override
public void showLoadFaluireView() {
mTitanic.cancel();
mRelativeLayoutLoadFaluire.setVisibility(View.VISIBLE);
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
}
@Override
public void showNoDataView() {
mTitanic.cancel();
mRelativeLayoutLoadNoData.setVisibility(View.VISIBLE);
mTextViewTip.setText("亲!您当前没有借阅书籍哦~");
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mRelativeLayoutLoading.setVisibility(View.GONE);
}
@Override
public void showMsg(String msg) {
CustomToast.showToast(this, msg, 2000);
}
@Override
protected void onDestroy() {
super.onDestroy();
queue.cancelAll(this);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/bookdetial/model/BookDetialModel.java
package com.tz.xiyoulibrary.activity.bookdetial.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.application.Application;
import com.tz.xiyoulibrary.utils.Constants;
import com.tz.xiyoulibrary.utils.JsonUtils;
import com.tz.xiyoulibrary.utils.LogUtils;
public class BookDetialModel implements IBookDetialModel {
public int state;
public String msg;
public Map<String, Object> bookDetial;
@Override
public void getBookDetial(RequestQueue queue, String url,
final CallBack<BookDetialModel> callBack) {
state = LOADING;
callBack.getModel(this);
StringRequest request = new StringRequest(Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.d("getBookDetial:", response);
// 解析数据
formatBookDetialDataByJson(response, callBack);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
state = LOADING_FALUIRE;
msg = "加载失败";
callBack.getModel(BookDetialModel.this);
}
});
request.setRetryPolicy(new DefaultRetryPolicy(Constants.TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
@Override
public void collection(RequestQueue queue, final String id,
final CallBack<BookDetialModel> callBack) {
state = LOADING;
callBack.getModel(this);
StringRequest request = new StringRequest(Method.POST,
Constants.GET_BOOK_ADD_FAVORITE,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.d("collection:", response);
// 解析数据
formatCollectionDataByJson(response, callBack);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
state = LOADING_FALUIRE;
msg = "网络异常";
callBack.getModel(BookDetialModel.this);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("session", Application.SESSION);
map.put("id", id);
return map;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(Constants.TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
/**
* 解析收藏数据
*/
protected void formatCollectionDataByJson(String response,
CallBack<BookDetialModel> callBack) {
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
state = LOADING_SUCCESS;
msg = getMsgByDetial(o.getString("Detail"));
} else {
state = LOADING_FALUIRE;
msg = "收藏失败";
}
} catch (Exception e) {
e.printStackTrace();
state = LOADING_FALUIRE;
msg = "收藏失败";
}
callBack.getModel(this);
}
private String getMsgByDetial(String detial) {
String s = null;
if (detial.equals("ADDED_SUCCEED")) {
s = "收藏成功";
} else if (detial.equals("ALREADY_IN_FAVORITE")) {
s = "已经收藏过了";
} else if (detial.equals("USER_NOT_LOGIN")) {
s = "用户登录失效,请重新登录";
} else if (detial.equals("PARAM_ERROR")) {
s = "参数错误,缺少参数";
} else {
s = "收藏失败";
}
return s;
}
/**
* 解析获取详情信息数据
*/
protected void formatBookDetialDataByJson(String response,
CallBack<BookDetialModel> callBack) {
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
bookDetial = new HashMap<String, Object>();
try {
JSONObject o2 = o.getJSONObject("Detail");
bookDetial.put("Title", o2.getString("Title"));
try {
bookDetial.put("Pub", o2.getString("Pub"));
} catch (Exception e) {
bookDetial.put("Pub", "暂无");
}
try {
bookDetial.put("Summary", o2.getString("Summary"));
} catch (Exception e) {
bookDetial.put("Summary", "暂无");
}
try {
bookDetial.put("Sort", o2.getString("Sort"));
} catch (Exception e) {
bookDetial.put("Sort", "暂无");
}
try {
bookDetial.put("ISBN", o2.getString("ISBN"));
} catch (Exception e) {
bookDetial.put("ISBN", "暂无");
}
try {
bookDetial.put("Author", o2.getString("Author"));
} catch (Exception e) {
bookDetial.put("Author", "暂无");
}
try {
bookDetial.put("ID", o2.getString("ID"));
} catch (Exception e) {
bookDetial.put("ID", "暂无");
}
try {
bookDetial.put("Form", o2.getString("Form"));
} catch (Exception e) {
bookDetial.put("Form", "暂无记录");
}
try {
bookDetial.put("Subject", o2.getString("Subject"));
} catch (Exception e) {
bookDetial.put("Subject", "暂无记录");
}
try {
bookDetial.put("RentTimes", o2.getString("RentTimes"));
} catch (Exception e) {
bookDetial.put("RentTimes", "暂无");
}
try {
bookDetial.put("FavTimes", o2.getString("FavTimes"));
} catch (Exception e) {
bookDetial.put("FavTimes", "暂无");
}
try {
bookDetial.put("BrowseTimes",
o2.getString("BrowseTimes"));
} catch (Exception e) {
bookDetial.put("BrowseTimes", "暂无");
}
try {
bookDetial.put("Total", o2.getString("Total"));
} catch (Exception e) {
bookDetial.put("Total", "暂无");
}
try {
bookDetial.put("Avaliable", o2.getString("Avaliable"));
} catch (Exception e) {
bookDetial.put("Avaliable", "暂无");
}
// 流通信息数组
LogUtils.d("BookDetial", "开始解析流通信息");
JSONArray array = o2.getJSONArray("CirculationInfo");
List<Map<String, String>> circulationInfoList = new ArrayList<Map<String, String>>();
int size = array.length() > 50 ? 50 : array.length();
for (int i = 0; i < size; i++) {
JSONObject o3 = array.getJSONObject(i);
Map<String, String> map = new HashMap<String, String>();
map.put("Barcode", o3.getString("Barcode"));
map.put("Sort", o3.getString("Sort"));
map.put("Department", o3.getString("Department"));
map.put("Status", o3.getString("Status"));
map.put("Date", o3.getString("Date"));
circulationInfoList.add(map);
}
bookDetial.put("CirculationInfo", circulationInfoList);
LogUtils.d("BookDetial", "流通信息解析完成");
LogUtils.d("BookDetial", "开始解析相关图书数据");
// 相关图书信息数组
JSONArray array2 = o2.getJSONArray("ReferBooks");
List<Map<String, String>> referBooksList = new ArrayList<Map<String, String>>();
for (int i = 0; i < array2.length(); i++) {
JSONObject o3 = array2.getJSONObject(i);
Map<String, String> map = new HashMap<String, String>();
map.put("ID", o3.getString("ID"));
map.put("Title", o3.getString("Title"));
map.put("Author", o3.getString("Author"));
referBooksList.add(map);
}
bookDetial.put("ReferBooks", referBooksList);
LogUtils.d("BookDetial", "相关推荐解析完成");
LogUtils.d("BookDetial", "开始解析来自豆瓣的数据");
// 来自豆瓣的信息,没有该书则为null
try {
JSONObject o3 = o2.getJSONObject("DoubanInfo");
if (o3.getString("Pages").equals("null")
|| o3.getString("Pages").equals("")) {
bookDetial.put("Pages", "暂无记录");
} else {
bookDetial.put("Pages", o3.getString("Pages")
+ " 页");
}
try {
JSONObject o4 = o3.getJSONObject("Images");
bookDetial.put("medium", o4.getString("large"));
// bookDetial.put("small", o3.getString("small"));
// bookDetial.put("large", o3.getString("large"));
} catch (Exception e) {
bookDetial.put("medium", "");
e.printStackTrace();
LogUtils.d("BookDetial", "解析豆瓣书籍图片异常");
}
bookDetial.put("Summary", o3.getString("Summary"));
bookDetial.put("Author_Info",
o3.getString("Author_Info"));
} catch (Exception e) {
bookDetial.put("Summary", "暂无");
bookDetial.put("Author_Info", "暂无");
bookDetial.put("Pages", "暂无记录");
bookDetial.put("medium", "");
}
state = LOADING_SUCCESS;
} catch (Exception e) {
Object[] object = JsonUtils.getErrorMsg(o
.getString("Detail"));
state = (Integer) object[0];
msg = (String) object[1];
}
} else {
state = LOADING_FALUIRE;
msg = "获取信息失败";
}
} catch (Exception e) {
e.printStackTrace();
state = LOADING_FALUIRE;
msg = "获取信息失败";
}
callBack.getModel(this);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/login/presenter/LoginPresenter.java
package com.tz.xiyoulibrary.activity.login.presenter;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.activity.login.model.ILoginModel;
import com.tz.xiyoulibrary.activity.login.model.LoginModel;
import com.tz.xiyoulibrary.activity.login.view.ILoginView;
public class LoginPresenter {
private ILoginView mLoginView;
private ILoginModel mLoginModel;
public LoginPresenter(ILoginView view) {
this.mLoginView = view;
mLoginModel = new LoginModel();
}
public void Login(RequestQueue queue) {
mLoginModel.login(queue, mLoginView.getUsername(), mLoginView.getPassword(),
new CallBack<LoginModel>() {
@Override
public void getModel(LoginModel model) {
switch (model.state) {
case ILoginModel.LOGIN_ING:
mLoginView.showDialog();
break;
case ILoginModel.LOGIN_FAILURE:
case ILoginModel.ACCOUNT_ERROR:
mLoginView.hideDialog();
mLoginView.showMsg(model.msg);
break;
case ILoginModel.LOGIN_SUCCESS:
mLoginView.hideDialog();
mLoginView.pushMainActivity();
break;
}
}
});
}
public void setUsername(Context context) {
mLoginView.setUsername(mLoginModel.getUsername(context));
}
public void setPassword(Context context) {
mLoginView.setPassword(mLoginModel.getPassword(context));
}
public void setIsSavePass(Context context) {
mLoginView.setIsSavePass(mLoginModel.getIsSavePass(context));
}
public void saveIsSavePass(Context context) {
mLoginModel.setIsSavePass(context, mLoginView.getIsSavePass());
}
public void setIsAutoLogin(Context context) {
mLoginView.setIsAutoLogin(mLoginModel.getIsAutoLogin(context));
}
public void saveIsAutoLogin(Context context) {
mLoginModel.setIsAutoLogin(context, mLoginView.getIsAutoLogin());
}
public void saveUsernameAndPassword(Context context) {
mLoginModel.saveUsernameAndPassword(context, mLoginView.getUsername(),
mLoginView.getPassword());
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/homedetail/presenter/HomeDetailPresenter.java
package com.tz.xiyoulibrary.activity.homedetail.presenter;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.activity.homedetail.model.HomeDetailModel;
import com.tz.xiyoulibrary.activity.homedetail.model.IHomeDetailModel;
import com.tz.xiyoulibrary.activity.homedetail.view.IHomeDetailView;
public class HomeDetailPresenter {
IHomeDetailModel detailModel;
IHomeDetailView detailView;
public HomeDetailPresenter(IHomeDetailView view){
detailModel = new HomeDetailModel();
this.detailView = view;
}
public void getHomeDetailData(RequestQueue queue,String url){
detailModel.getDetailData(queue, url, new CallBack<HomeDetailModel>() {
@Override
public void getModel(HomeDetailModel model) {
// TODO Auto-generated method stub
switch (model.status) {
case IHomeDetailModel.LOADING:
detailView.showLoadingView();
break;
case IHomeDetailModel.LOADING_FALUIRE:
detailView.showLoadFailView();
detailView.showMsg(model.message);
break;
case IHomeDetailModel.LOADING_SUCCESS:
System.out.println("已经到presenter的加载成功");
detailView.showDetailData(model.detailMap);
break;
case IHomeDetailModel.NO_DATA:
detailView.showNoDataView();
break;
}
}
});
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/callback/CallBack.java
package com.tz.xiyoulibrary.activity.callback;
public interface CallBack<T> {
public void getModel(T model);
}
<file_sep>/src/com/tz/xiyoulibrary/activity/rank/view/IRankView.java
package com.tz.xiyoulibrary.activity.rank.view;
import java.util.List;
import java.util.Map;
public interface IRankView {
void showLoadingView();
void showRankView(List<Map<String, String>> rankData);
void showLoadFaluireView();
void showNoDataView();
void showMsg(String msg);
void showRefershFaluireView();
void showUpRefershView(List<Map<String, String>> rankData);
void showDownRefershView(List<Map<String, String>> rankData);
}
<file_sep>/src/com/tz/xiyoulibrary/activity/myfoot/view/MyFootAdapter.java
package com.tz.xiyoulibrary.activity.myfoot.view;
import java.util.List;
import android.content.Context;
import android.text.TextUtils;
import android.widget.ImageView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.bean.BookBean;
import com.tz.xiyoulibrary.utils.adapter.CommonAdapter;
import com.tz.xiyoulibrary.utils.adapter.ViewHolder;
public class MyFootAdapter extends CommonAdapter<BookBean> {
private ImageLoader imageLoader;
public MyFootAdapter(Context context, List<BookBean> mDatas,
int itemLayoutId, ImageLoader imageLoader) {
super(context, mDatas, itemLayoutId);
this.imageLoader = imageLoader;
}
@Override
public void convert(ViewHolder helper, BookBean b) {
helper.setText(R.id.tv_book_title_item_myfoot, b.getTitle());
helper.setText(R.id.tv_book_author_item_myborrow, b.getState());
helper.setText(R.id.tv_book_pub_item_myfoot, b.getDate());
helper.setText(R.id.tv_book_id_item_myfoot, b.getBarCode());
ImageView bookImg = helper.getView(R.id.iv_book_img_item_myfoot);
String imgUrl = b.getImgUrl();
bookImg.setTag(imgUrl);
if (TextUtils.equals(imgUrl, "")) {
bookImg.setBackgroundResource(R.drawable.img_book_no);
} else if (bookImg.getTag().toString().equals(imgUrl)) {
ImageListener imageListener = ImageLoader.getImageListener(bookImg,
R.drawable.img_book, R.drawable.img_book_no);
imageLoader.get(imgUrl, imageListener, 240, 320);
}
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/login/model/LoginModel.java
package com.tz.xiyoulibrary.activity.login.model;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.tz.xiyoulibrary.activity.callback.CallBack;
import com.tz.xiyoulibrary.application.Application;
import com.tz.xiyoulibrary.bean.UserBean;
import com.tz.xiyoulibrary.utils.ConfigFile;
import com.tz.xiyoulibrary.utils.Constants;
import com.tz.xiyoulibrary.utils.LogUtils;
public class LoginModel implements ILoginModel {
public int state;
public String msg;
@Override
public void login(final RequestQueue queue, final String username,
final String password, final CallBack<LoginModel> callBack) {
if (checkInput(username, password)) {
state = LOGIN_ING;
callBack.getModel(this);
StringRequest request = new StringRequest(Method.POST,
Constants.GET_USER_LOGIN, new Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.d("LoginResponse:", response);
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
state = LOGIN_SUCCESS;
msg = o.getString("Detail");
Application.SESSION = msg;
Application.USERNAME = username;
getUserInfo(queue, msg, callBack);
} else {
state = LOGIN_FAILURE;
if (o.getString("Detail").equals(
"ACCOUNT_ERROR")) {
msg = "Õ˺ŴíÎó£¬ÃÜÂë´íÎó»òÕË»§²»´æÔÚ";
} else {
msg = "µÇ¼ʧ°Ü";
}
callBack.getModel(LoginModel.this);
}
} catch (JSONException e) {
e.printStackTrace();
state = LOGIN_FAILURE;
msg = "µÇ¼ʧ°Ü";
callBack.getModel(LoginModel.this);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
state = LOGIN_FAILURE;
msg = "ÍøÂçÇëÇóʧ°Ü";
callBack.getModel(LoginModel.this);
}
}) {
@Override
protected Map<String, String> getParams()
throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", <PASSWORD>);
return map;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(Constants.TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
} else {
state = LOGIN_FAILURE;
callBack.getModel(this);
}
}
@Override
public void getUserInfo(RequestQueue queue, final String session,
final CallBack<LoginModel> callBack) {
StringRequest request = new StringRequest(Method.POST,
Constants.GET_USER_INFO, new Listener<String>() {
@Override
public void onResponse(String response) {
LogUtils.d("LoginResponse:", response);
try {
JSONObject o = new JSONObject(response);
if (o.getBoolean("Result")) {
state = LOGIN_SUCCESS;
JSONObject info = o.getJSONObject("Detail");
UserBean user = new UserBean();
user.setId(info.getString("ID"));
user.setName(info.getString("Name"));
user.setFromData(info.getString("From"));
user.setToData(info.getString("To"));
user.setReaderType(info.getString("ReaderType"));
user.setDepartment(info.getString("Department"));
user.setDebt(info.get("Debt") + "");
Application.user = user;
callBack.getModel(LoginModel.this);
} else {
state = LOGIN_FAILURE;
msg = "µÇ¼ʧ°Ü";
callBack.getModel(LoginModel.this);
}
} catch (JSONException e) {
e.printStackTrace();
state = LOGIN_FAILURE;
msg = "µÇ¼ʧ°Ü";
callBack.getModel(LoginModel.this);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
state = LOGIN_FAILURE;
msg = "ÍøÂçÇëÇóʧ°Ü";
callBack.getModel(LoginModel.this);
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("session", session);
return map;
}
};
queue.add(request);
}
@Override
public String getUsername(Context context) {
return ConfigFile.getUsername(context);
}
@Override
public String getPassword(Context context) {
return ConfigFile.getPassword(context);
}
@Override
public void saveUsernameAndPassword(Context context, String username,
String password) {
ConfigFile.savePassword(context, password);
ConfigFile.saveUsername(context, username);
}
@Override
public boolean getIsSavePass(Context context) {
return ConfigFile.getIsSavePass(context);
}
@Override
public void setIsSavePass(Context context, boolean isSavePass) {
ConfigFile.saveIsSavePass(context, isSavePass);
}
@Override
public boolean getIsAutoLogin(Context context) {
return ConfigFile.getIsAutoLogin(context);
}
@Override
public void setIsAutoLogin(Context context, boolean isAutoLogin) {
ConfigFile.saveIsAutoLogin(context, isAutoLogin);
}
@Override
public boolean checkInput(String username, String password) {
if (username.equals("")) {
msg = "Óû§Ãû²»ÄÜΪ¿Õ";
return false;
}
if (password.equals("")) {
msg = "ÃÜÂë²»ÄÜΪ¿Õ";
return false;
}
return true;
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/myfoot/view/MyFootActivity.java
package com.tz.xiyoulibrary.activity.myfoot.view;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.activity.baseactivity.BaseActivity;
import com.tz.xiyoulibrary.activity.bookdetial.view.BookDetialActivity_;
import com.tz.xiyoulibrary.activity.myfoot.presenter.MyFootPresenter;
import com.tz.xiyoulibrary.bean.BookBean;
import com.tz.xiyoulibrary.titanicview.Titanic;
import com.tz.xiyoulibrary.titanicview.TitanicTextView;
import com.tz.xiyoulibrary.titanicview.Typefaces;
import com.tz.xiyoulibrary.toastview.CustomToast;
import com.tz.xiyoulibrary.utils.BitmapCache;
import com.tz.xiyoulibrary.utils.Constants;
/**
*
* @author Administrator 我的收藏
*/
@EActivity(R.layout.activity_myfoot)
public class MyFootActivity extends BaseActivity implements IMyFootView {
@ViewById(R.id.rl_back_actionbar)
RelativeLayout mRelativeLayoutBack;
@ViewById(R.id.tv_title_actionbar)
TextView mTextViewTitle;
Titanic mTitanic;
@ViewById(R.id.loading_text)
TitanicTextView mTitanicTextView;
@ViewById(R.id.rl_loading)
RelativeLayout mRelativeLayoutLoading;
@ViewById(R.id.rl_load_faluire)
RelativeLayout mRelativeLayoutLoadFaluire;
@ViewById(R.id.rl_load_no_data)
RelativeLayout mRelativeLayoutLoadNoData;
@ViewById(R.id.tv_load_no_data_tip)
TextView mTextViewTip;
private RequestQueue queue;
private ImageLoader imageLoader;
private List<BookBean> favoriteData;
private MyFootPresenter mPresenter;
@ViewById(R.id.lv_favorite_activity_myfoot)
ListView mListViewMyFoot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue = Volley.newRequestQueue(MyFootActivity.this);
imageLoader = new ImageLoader(queue, new BitmapCache());
mPresenter = new MyFootPresenter(this);
}
@AfterViews
public void initWidgetAfter() {
mTitanicTextView
.setTypeface(Typefaces.get(this, "Satisfy-Regular.ttf"));
mTitanic = new Titanic();
mRelativeLayoutBack.setVisibility(View.VISIBLE);
mTextViewTitle.setText("我的足迹");
// 获取历史详情
getFavoriteData();
}
/**
* 获取历史详情
*/
private void getFavoriteData() {
mPresenter.getFavoriteData(queue);
}
@Override
public void showLoadingView() {
mRelativeLayoutLoading.setVisibility(View.VISIBLE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mTitanic.start(mTitanicTextView);
}
@Override
public void showFavoriteView(List<BookBean> favoriteData) {
// 关闭加载动画
mTitanic.cancel();
// 隐藏加载视图
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
this.favoriteData = favoriteData;
MyFootAdapter adapter = new MyFootAdapter(MyFootActivity.this,
this.favoriteData, R.layout.item_activity_myfoot,imageLoader);
mListViewMyFoot.setAdapter(adapter);
mListViewMyFoot.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView tv = (TextView) view
.findViewById(R.id.tv_book_id_item_myfoot);
Intent intent = new Intent(MyFootActivity.this,
BookDetialActivity_.class);
intent.putExtra("url", Constants.GET_BOOK_DETAIL_BY_BARCODE
+ tv.getText().toString());
startActivity(intent);
}
});
}
@Override
public void showLoadFaluireView() {
mTitanic.cancel();
mRelativeLayoutLoadFaluire.setVisibility(View.VISIBLE);
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
}
@Override
public void showNoDataView() {
mTitanic.cancel();
mRelativeLayoutLoadNoData.setVisibility(View.VISIBLE);
mTextViewTip.setText("亲!您还没有借过书呢~");
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mRelativeLayoutLoading.setVisibility(View.GONE);
}
@Click(R.id.rl_back_actionbar)
public void back() {
finish();
}
@Click(R.id.rl_load_faluire)
public void resetData(){
getFavoriteData();
}
@Override
public void showMsg(String msg) {
CustomToast.showToast(this, msg, 2000);
}
}
<file_sep>/src/com/tz/xiyoulibrary/activity/myfoot/model/IMyFootModel.java
package com.tz.xiyoulibrary.activity.myfoot.model;
import com.android.volley.RequestQueue;
import com.tz.xiyoulibrary.activity.callback.CallBack;
public interface IMyFootModel {
static final int LOADING_SUCCESS = 0;
static final int LOADING_FALUIRE = 1;
static final int NO_DATA = 2;
static final int LOADING = 3;
void getFavoriteData(RequestQueue queue, CallBack<MyFootModel> callBack);
}
<file_sep>/src/com/tz/xiyoulibrary/activity/bookdetial/view/BookDetialActivity.java
package com.tz.xiyoulibrary.activity.bookdetial.view;
import java.util.List;
import java.util.Map;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ImageView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.tencent.tauth.Tencent;
import com.tz.xiyoulibrary.R;
import com.tz.xiyoulibrary.activity.baseactivity.BaseActivity;
import com.tz.xiyoulibrary.activity.bookdetial.presenter.BookDetialPresenter;
import com.tz.xiyoulibrary.pulltozoomview.PullToZoomListView;
import com.tz.xiyoulibrary.titanicview.Titanic;
import com.tz.xiyoulibrary.titanicview.TitanicTextView;
import com.tz.xiyoulibrary.titanicview.Typefaces;
import com.tz.xiyoulibrary.toastview.CustomToast;
import com.tz.xiyoulibrary.utils.BitmapCache;
import com.tz.xiyoulibrary.utils.Constants;
@EActivity(R.layout.activity_book_detial)
public class BookDetialActivity extends BaseActivity implements IBookDetialView {
@ViewById(R.id.rl_back_actionbar)
RelativeLayout mRelativeLayoutBack;
@ViewById(R.id.tv_title_actionbar)
TextView mTextViewTitle;
Titanic mTitanic;
@ViewById(R.id.loading_text)
TitanicTextView mTitanicTextView;
@ViewById(R.id.rl_loading)
RelativeLayout mRelativeLayoutLoading;
@ViewById(R.id.rl_load_faluire)
RelativeLayout mRelativeLayoutLoadFaluire;
@ViewById(R.id.rl_load_no_data)
RelativeLayout mRelativeLayoutLoadNoData;
@ViewById(R.id.tv_load_no_data_tip)
TextView mTextViewNoDataTip;
@ViewById(R.id.tv_load_faluire_tip)
TextView mTextViewLoadFaluireTip;
private RequestQueue queue;
private ImageLoader imageLoader;
@ViewById(R.id.ptzv_book_detial)
PullToZoomListView mPullToZoomListView;
private Map<String, Object> bookDetial;
private String url;
private BookDetialPresenter mPresenter;
private ProgressDialog progressDialog;
Tencent mTencent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queue = Volley.newRequestQueue(BookDetialActivity.this);
url = getIntent().getStringExtra("url");
mPresenter = new BookDetialPresenter(this);
imageLoader = new ImageLoader(queue, new BitmapCache());
progressDialog = new ProgressDialog(BookDetialActivity.this);
progressDialog.setTitle("提示");
progressDialog.setMessage("收藏中,请稍候...");
progressDialog.setCancelable(false);
ShareSDK.initSDK(this);
}
@AfterViews
public void initWidgetAfter() {
mTitanicTextView
.setTypeface(Typefaces.get(this, "Satisfy-Regular.ttf"));
mTitanic = new Titanic();
mRelativeLayoutBack.setVisibility(View.VISIBLE);
mTextViewTitle.setText("图书详情");
// 获取图书详情
getBookDetial();
}
/**
* 获取图书详情
*/
private void getBookDetial() {
mPresenter.getBookDetial(queue, url);
}
@Click(R.id.rl_back_actionbar)
public void back() {
finish();
}
@Click(R.id.rl_load_faluire)
public void resetGetData() {
getBookDetial();
}
@Override
public void showLoadingView() {
mRelativeLayoutLoading.setVisibility(View.VISIBLE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mTitanic.start(mTitanicTextView);
}
@Override
public void showBookDetialView(Map<String, Object> bookDetial) {
// 关闭加载动画
mTitanic.cancel();
// 隐藏加载视图
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
this.bookDetial = bookDetial;
LayoutInflater inflater = LayoutInflater.from(BookDetialActivity.this);
RelativeLayout foot = (RelativeLayout) inflater.inflate(
R.layout.activity_book_detial_foot, null);
// 初始化基本资料
addOneView(foot);
// 添加流通情况
addTwoView(foot);
// 添加图书摘要
addThreeView(foot);
// 添加相关推荐
addFourView(foot);
mPullToZoomListView.addFooterView(foot);
String[] adapterData = new String[] {};
mPullToZoomListView.setAdapter(new ArrayAdapter<String>(
BookDetialActivity.this, android.R.layout.simple_list_item_1,
adapterData));
String imgUrl;
try {
imgUrl = bookDetial.get("medium").toString();
} catch (Exception e) {
imgUrl = "";
}
if (TextUtils.equals(imgUrl, "")) {
mPullToZoomListView.getHeaderView().setImageResource(
R.drawable.img_book_no);
} else {
ImageListener listener = ImageLoader.getImageListener(
mPullToZoomListView.getHeaderView(),
R.drawable.img_book_no, R.drawable.img_book_no);
imageLoader.get(imgUrl, listener);
}
mPullToZoomListView.getHeaderView().setScaleType(
ImageView.ScaleType.CENTER_CROP);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
}
/**
* 添加相关推荐
*/
private void addFourView(RelativeLayout root) {
ListView lv = (ListView) root
.findViewById(R.id.lv_refer_activity_book_detial);// 流通情况
@SuppressWarnings("unchecked")
ReferAdapter adapter = new ReferAdapter(BookDetialActivity.this,
(List<Map<String, String>>) bookDetial.get("ReferBooks"),
R.layout.item_refer_adapter);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView tv = (TextView) view
.findViewById(R.id.tv_id_item_refer);
Intent intent = new Intent(BookDetialActivity.this,
BookDetialActivity_.class);
intent.putExtra("url", Constants.GET_BOOK_DETAIL_BY_ID
+ tv.getText().toString());
startActivity(intent);
}
});
}
/**
* 添加图书摘要
*/
private void addThreeView(RelativeLayout root) {
TextView tv_no_data = (TextView) root
.findViewById(R.id.tv_no_book_detial);
LinearLayout ll = (LinearLayout) root.findViewById(R.id.ll_book_detial);
if (!bookDetial.get("Author_Info").equals("")) {
tv_no_data.setVisibility(View.GONE);
ll.setVisibility(View.VISIBLE);
TextView tv = (TextView) root
.findViewById(R.id.tv_book_author_info_activity_book_detial);
tv.setText(bookDetial.get("Author_Info") + "");
} else {
root.findViewById(R.id.ll_book_author_info_activity_book_detial)
.setVisibility(View.GONE);
}
if (!bookDetial.get("Summary").equals("")) {
tv_no_data.setVisibility(View.GONE);
ll.setVisibility(View.VISIBLE);
TextView tv = (TextView) root
.findViewById(R.id.tv_book_Summary_activity_book_detial);
tv.setText(bookDetial.get("Summary") + "");
} else {
root.findViewById(R.id.ll_book_Summary_activity_book_detial)
.setVisibility(View.GONE);
}
if (bookDetial.containsKey("Author_Info")
&& bookDetial.get("Summary").equals("")) {
ll.setVisibility(View.GONE);
tv_no_data.setVisibility(View.VISIBLE);
}
}
/**
* 流通情况
*/
private void addTwoView(RelativeLayout root) {
TextView tv;
tv = (TextView) root
.findViewById(R.id.tv_book_avaliable_activity_book_detial_two);// 可借数量
tv.setText(bookDetial.get("Avaliable") + " 本");
tv = (TextView) root
.findViewById(R.id.tv_book_total_activity_book_detial_two);// 藏书数量
tv.setText(bookDetial.get("Total") + " 本");
ListView lv = (ListView) root
.findViewById(R.id.lv_circlu_activity_book_detial);// 流通情况
@SuppressWarnings("unchecked")
CirculationAdapter adapter = new CirculationAdapter(
BookDetialActivity.this,
(List<Map<String, String>>) bookDetial.get("CirculationInfo"),
R.layout.item_circulation_adapter);
lv.setAdapter(adapter);
}
/**
* 基本资料
*/
private void addOneView(RelativeLayout root) {
Button collection = (Button) root
.findViewById(R.id.bt_collection_activity_book_detial);
Button share = (Button) root
.findViewById(R.id.bt_share_activity_book_detial);
collection.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mPresenter.collection(queue, bookDetial.get("ID") + "");
}
});
share.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showShare(BookDetialActivity.this, null, true);
}
});
TextView tv;
tv = (TextView) root.findViewById(R.id.tv_title_activity_book_detial);// 标题
tv.setText(bookDetial.get("Title") + "");
tv = (TextView) root.findViewById(R.id.tv_book_id_activity_book_detial);// 索书号
tv.setText(bookDetial.get("Sort") + "");
tv = (TextView) root
.findViewById(R.id.tv_book_author_activity_book_detial);// 作者
tv.setText(bookDetial.get("Author") + "");
tv = (TextView) root
.findViewById(R.id.tv_book_page_activity_book_detial);// 页数
try {
tv.setText(bookDetial.get("Pages") + "");
} catch (Exception e) {
tv.setText(bookDetial.get("Form") + "");
}
tv = (TextView) root
.findViewById(R.id.tv_book_avaliable_activity_book_detial);// 可借数量
tv.setText(bookDetial.get("Avaliable") + " 本");
tv = (TextView) root
.findViewById(R.id.tv_book_renttimes_activity_book_detial);// 借阅次数
tv.setText(bookDetial.get("RentTimes") + " 次");
tv = (TextView) root
.findViewById(R.id.tv_book_favtimes_activity_book_detial);// 收藏次数
tv.setText(bookDetial.get("FavTimes") + " 次");
tv = (TextView) root
.findViewById(R.id.tv_book_browsetimes_activity_book_detial);// 浏览次数
tv.setText(bookDetial.get("BrowseTimes") + " 次");
tv = (TextView) root
.findViewById(R.id.tv_book_total_activity_book_detial);// 藏书数量
tv.setText(bookDetial.get("Total") + " 本");
tv = (TextView) root
.findViewById(R.id.tv_book_subject_activity_book_detial);// 主题分类
tv.setText(bookDetial.get("Subject") + "");
tv = (TextView) root
.findViewById(R.id.tv_book_pub_activity_book_detial);// 出版社
tv.setText(bookDetial.get("Pub") + "");
}
@Override
public void showLoadFaluireView() {
mTitanic.cancel();
mRelativeLayoutLoadFaluire.setVisibility(View.VISIBLE);
mTextViewNoDataTip.setText("亲!查询失败了~");
mRelativeLayoutLoading.setVisibility(View.GONE);
mRelativeLayoutLoadNoData.setVisibility(View.GONE);
}
@Override
public void showNoDataView() {
mTitanic.cancel();
mRelativeLayoutLoadNoData.setVisibility(View.VISIBLE);
mTextViewNoDataTip.setText("亲!没有该书籍相关信息~");
mRelativeLayoutLoadFaluire.setVisibility(View.GONE);
mRelativeLayoutLoading.setVisibility(View.GONE);
}
@Override
public void showMsg(String msg) {
CustomToast.showToast(this, msg, 2000);
}
@Override
protected void onDestroy() {
super.onDestroy();
queue.cancelAll(this);
}
@Override
public void hidenDialog() {
progressDialog.dismiss();
}
@Override
public void showDialog() {
progressDialog.show();
}
/**
* 演示调用ShareSDK执行分享
*
* @param context
* @param platformToShare
* 指定直接分享平台名称(一旦设置了平台名称,则九宫格将不会显示)
* @param showContentEdit
* 是否显示编辑页
*/
private void showShare(Context context, String platformToShare,
boolean showContentEdit) {
OnekeyShare oks = new OnekeyShare();
oks.setSilent(!showContentEdit);
if (platformToShare != null) {
oks.setPlatform(platformToShare);
}
// ShareSDK快捷分享提供两个界面第一个是九宫格 CLASSIC 第二个是SKYBLUE
oks.setTheme(OnekeyShareTheme.CLASSIC);
// 令编辑页面显示为Dialog模式
oks.setDialogMode();
// 在自动授权时可以禁用SSO方式
oks.disableSSOWhenAuthorize();
String imgUrl = bookDetial.get("medium").toString();
oks.setTitle("西邮图书馆---" + "《" + bookDetial.get("Title") + "》");
oks.setTitleUrl("http://lib.xiyoumobile.com/moreInfo.html?id="
+ bookDetial.get("ID").toString());
oks.setText(bookDetial.get("Summary") + "");
// oks.setImagePath("/sdcard/test-pic.jpg"); //分享sdcard目录下的图片
if (!TextUtils.equals(imgUrl, "")) {
oks.setImageUrl(imgUrl);
} else {
// oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
}
oks.setComment("分享"); // 我对这条分享的评论,仅在人人网和QQ空间使用,否则可以不提供
oks.setSite("西邮图书馆"); // QZone分享完之后返回应用时提示框上显示的名称
oks.setSiteUrl("http://lib.xiyoumobile.com/moreInfo.html?id="
+ bookDetial.get("ID").toString());// QZone分享参数
oks.setSiteUrl(imgUrl);// QZone分享参数
oks.setVenueName("西邮图书馆");
oks.setVenueDescription("form xiyouLibrary");
oks.setShareFromQQAuthSupport(false);
// 将快捷分享的操作结果将通过OneKeyShareCallback回调
// oks.setCallback(new OneKeyShareCallback());
// 去自定义不同平台的字段内容
// oks.setShareContentCustomizeCallback(new
// ShareContentCustomizeDemo());
// 在九宫格设置自定义的图标
/*
* Bitmap enableLogo = BitmapFactory.decodeResource(
* context.getResources(), R.drawable.ssdk_oks_logo_qzone); Bitmap
* disableLogo = BitmapFactory.decodeResource( context.getResources(),
* R.drawable.ssdk_oks_logo_qzone); String label = "QQ空间";
* OnClickListener listener = new OnClickListener() { public void
* onClick(View v) { shareToQQzone(); } };
* oks.setCustomerLogo(enableLogo, disableLogo, label, listener);
*/
// 隐藏支付宝
// 为EditPage设置一个背景的View
// oks.setEditPageBackground(getPage());
// 隐藏九宫格中的新浪微博
// oks.addHiddenPlatform(SinaWeibo.NAME);
// String[] AVATARS = {
// "http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
// "http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
// "http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
// "http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg"
// };
// oks.setImageArray(AVATARS); //腾讯微博和twitter用此方法分享多张图片,其他平台不可以
// 启动分享
oks.show(context);
}
}
| eaf8079d74e0d5db133a22813c7e167134f886fa | [
"Java"
] | 34 | Java | xyTianZhao/XiyouLibrary | 70ea1d5492c229549202b9d245441683a0b22fbb | bf74239468bc3dd43ffa535c9fcdf5e141ec1db6 | |
refs/heads/master | <file_sep><?php namespace App\Controllers;
class Detail_Kapal extends BaseController
{
public function index()
{
return view('Detail_Kapal');
}
//--------------------------------------------------------------------
}<file_sep><?php namespace App\Controllers;
use App\Models\TiketModel;
class Edit_Tiket extends BaseController
{
// public function index()
// {
// return view('edit_tiket');
// }
public function edit($id)
{
$model = new TiketModel();
$data = $model->find($id);
return view("edit_tiket", ["data" => $data]);
}
//--------------------------------------------------------------------
}<file_sep><?php namespace App\Controllers;
class Bayar extends BaseController
{
public function index()
{
return view('bayar');
}
//--------------------------------------------------------------------
}<file_sep><?php echo $this->include('User/header'); ?>
<?= $this->renderSection('content'); ?>
<?php echo $this->include('User/footer'); ?><file_sep><?= $this->extend('user/template'); ?>
<?= $this->section('content'); ?>
<div class="buttom">
<h1>TIKET TRAVEL</h1>
<span>Cek Dan Pesan Tiket Anda Disini</span>
<br>
</div>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link disabled" href="home" tabindex="-1" aria-disabled="true">Pesawat</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kereta" tabindex="-1" aria-disabled="true">Kereta</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kapal" tabindex="-1" aria-disabled="true">Kapal</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_bus" tabindex="-1" aria-disabled="true">Bus</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/login" tabindex="-1" aria-disabled="true">Login</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/register" tabindex="-1" aria-disabled="true">Register</a>
</li>
</ul>
<div class="jumbotron">
<div class="container">
<table class="table table-bordered">
<thead>
<tr bgcolor="#8e8eff">
<th scope="col">Konfirmasi Pembayaran</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">
<div class="mb-3">
<label for="inputBooking" class="form-label">No. Booking</label>
<input type="text" class="form-control" id="inputBooking" style="background-color: #e9ecef" disabled>
</div>
<div class="mb-3">
<label for="inputBayar" class="form-label">Total Bayar</label>
<input type="text" class="form-control" id="inputBayar" style="background-color: #e9ecef" disabled>
</div>
<div class="input-group mb-3">
<label class="input-group-text" for="inputGroupFile01">Foto/Screenshot Bukti Transaksi</label>
<input type="file" class="form-control" id="inputGroupFile01">
</div>
</th>
</tr>
</tbody>
</table>
<a href="checkout" class="btn btn-success">Konfirmasi</a>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php namespace App\Controllers;
class Detail_BUs extends BaseController
{
public function index()
{
return view('Detail_Bus');
}
//--------------------------------------------------------------------
}<file_sep><?= $this->extend('user/template'); ?>
<?= $this->section('content'); ?>
<div class="buttom">
<h1>DASHBOARD</h1>
<span>Selamat Datang Di Tiket Travel</span>
<div class="jumbotron">
<div class="container">
<nav class="navbar navbar-light bg-light">
<form class="container-fluid justify-content-start">
<a href="home"><button class="btn btn-outline-success me-2" type="button">Home</button></a>
<a href="auth/login"><button class="btn btn-outline-success me-2" type="button">Login</button></a>
<a href="auth/register"><button class="btn btn-outline-success me-2" type="button">Register</button></a>
</form>
</nav>
</div>
</div>
</div>
<br>
<div class="jumbotron">
<div class="container">
<table class="table table-bordered">
<thead>
<tr bgcolor="#8e8eff">
<th scope="col">No</th>
<th scope="col">Penyedia</th>
<th scope="col">Waktu</th>
<th scope="col">Jurusan</th>
<th scope="col">Kelas</th>
<th scope="col">Harga Tiket</th>
<th scope="col">Kursi</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"></th>
<?php $i=1; ?>
<?php foreach($data as $b) : ?>
<tr>
<!-- <th scope="row"><?= $i++;?> </th> -->
<td><?= $b['id'];?></td>
<td><?= $b['penyedia'];?></td>
<td><?= $b['waktu'];?></td>
<td><?= $b['jurusan'];?></td>
<td><?= $b['kelas'];?></td>
<td><?= $b['harga'];?></td>
<td><?= $b['kursi'];?></td>
</tr>
<?php endforeach; ?>
</tr>
</tbody>
</table>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?= $this->extend('User/template'); ?>
<?= $this->section('content'); ?>
<div class="buttom">
<h1>TIKET TRAVEL</h1>
<span>Cek Dan Pesan Tiket Anda Disini</span>
</div>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link disabled" href="home" tabindex="-1" aria-disabled="true">Pesawat</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kereta" tabindex="-1" aria-disabled="true">Kereta</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kapal" tabindex="-1" aria-disabled="true">Kapal</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_bus" tabindex="-1" aria-disabled="true">Bus</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/login" tabindex="-1" aria-disabled="true">Login</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/register" tabindex="-1" aria-disabled="true">Register</a>
</li>
</ul>
<div class="jumbotron">
<div class="container">
<form>
<div class="row mb-3">
<label for="inputPesawat" class="col-sm-1 col-form-label">Penyedia</label>
<div class="col-sm-6">
<input type="jenis pesawat" class="form-control" id="inputPesawat" style="background-color: #e9ecef" disabled>
</div>
</div>
<div class="row mb-3">
<label for="inputWaktu" class="col-sm-1 col-form-label">Waktu</label>
<div class="col-sm-6">
<input type="Waktu" class="form-control" id="inputWaktu" style="background-color: #e9ecef" disabled>
</div>
</div>
<div class="row mb-3">
<label for="inputJurusan" class="col-sm-1 col-form-label">Jurusan</label>
<div class="col-sm-6">
<input type="Jurusan" class="form-control" id="inputJurusan" style="background-color: #e9ecef" disabled>
</div>
</div>
<div class="row mb-3">
<label for="inputKelas" class="col-sm-1 col-form-label">Kelas</label>
<div class="col-sm-6">
<input type="Kelas" class="form-control" id="inputKelas" style="background-color: #e9ecef" disabled>
</div>
</div>
<div class="row mb-3">
<label for="inputPenumpang" class="col-sm-1 col-form-label">Jumlah Penumpang</label>
<div class="col-sm-6">
<input type="Jumlah Penumpang" class="form-control" id="inputPenumpang" style="background-color: #e9ecef" disabled>
</div>
</div>
<div class="row mb-3">
<label for="inputTotal" class="col-sm-1 col-form-label">Total Harga</label>
<div class="col-sm-6">
<input type="Total Hrga" class="form-control" id="inputTotal" style="background-color: #e9ecef" disabled>
</div>
</div>
<ul type="disc">
<li><font color="blue"> reservasi dapat dilakukan 1x24 jam sebelum armada berangkat
</font>
</li>
<li>
<font color="blue">Harga dan ketersediaan tempat duduk sewaktu waktu dapat berubah</font>
</li>
</ul>
<br>
<div class="row mb-3">
<div class="col-sm-10 offset-sm-2">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck1">
<label class="form-check-label" for="gridCheck1">
Saya menyetujui ketentuan dan persyaratan diatas
</label>
</div>
</div>
</div>
<a href="detail_pesan" class="btn btn-success">Selanjutnya</a>
</form>
</div>
</div>
<?= $this->endSection(); ?><file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 15, 2021 at 04:20 PM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.2.34
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `tiket`
--
-- --------------------------------------------------------
--
-- Table structure for table `tiket`
--
CREATE TABLE `tiket` (
`id` int(4) NOT NULL,
`penyedia` varchar(50) NOT NULL,
`waktu` date NOT NULL,
`jurusan` varchar(50) NOT NULL,
`kelas` varchar(50) NOT NULL,
`harga` int(15) NOT NULL,
`kursi` int(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `tiket`
--
INSERT INTO `tiket` (`id`, `penyedia`, `waktu`, `jurusan`, `kelas`, `harga`, `kursi`) VALUES
(14, 'sriwijaya', '2021-01-01', 'bali', 'ekonomi', 5000, 500),
(15, 'garuda', '2021-01-08', 'jogjkarta', 'ekonomi', 100, 12),
(16, 'first travel', '2021-01-16', 'jakarta', 'bisnis', 1000, 30);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_level` int(1) NOT NULL DEFAULT 2,
`user_name` varchar(100) DEFAULT NULL,
`user_email` varchar(100) DEFAULT NULL,
`user_password` varchar(200) DEFAULT NULL,
`user_created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `user_level`, `user_name`, `user_email`, `user_password`, `user_created_at`) VALUES
(1, 1, 'admin', '<EMAIL>', <PASSWORD>', '2020-12-07 07:59:01'),
(3, 2, 'asep', '<EMAIL>', <PASSWORD>', '2020-12-07 08:01:19'),
(4, 2, 'buds', '<EMAIL>', <PASSWORD>', '2020-12-08 03:26:22'),
(5, 2, 'asd', '<EMAIL>', <PASSWORD>', '2021-01-05 07:53:32'),
(6, 2, 'budi su budu', '<EMAIL>', '$2y$10$iewfcypPi1WHiO2UzHMhHOm/f0Hm77.14vTOS4iJRbDTJzMHxzow.', '2021-01-15 07:28:03'),
(7, 2, 'praktek', '<EMAIL>', <PASSWORD>1/O0ve7rf.dgHom<PASSWORD>com0<PASSWORD>4YcVB3m', '2021-01-15 10:21:36');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tiket`
--
ALTER TABLE `tiket`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?= $this->extend('user/template'); ?>
<?= $this->section('content'); ?>
<div class="buttom">
<h1>TIKET TRAVEL</h1>
<span>Cek Dan Pesan Tiket Anda Disini</span>
<br>
</div>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link disabled" href="home" tabindex="-1" aria-disabled="true">Pesawat</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kereta" tabindex="-1" aria-disabled="true">Kereta</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kapal" tabindex="-1" aria-disabled="true">Kapal</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_bus" tabindex="-1" aria-disabled="true">Bus</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/login" tabindex="-1" aria-disabled="true">Login</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/register" tabindex="-1" aria-disabled="true">Register</a>
</li>
</ul>
<div class="jumbotron">
<div class="container">
<table class="table table-bordered">
<thead>
<tr bgcolor="#8e8eff">
<th scope="col">Info perjalanan</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">
<div class="mb-3">
<label for="inputPesawat" class="form-label">Penyedia</label>
<input type="text" class="form-control" id="inputPesawat" style="background-color: #e9ecef" disabled>
</div>
<div class="mb-3">
<label for="inputWaktu" class="form-label">Waktu</label>
<input type="text" class="form-control" id="inputWaktu" style="background-color: #e9ecef" disabled>
</div>
<div class="mb-3">
<label for="inputJurusan" class="form-label">Jurusan</label>
<input type="text" class="form-control" id="inputJurusan" style="background-color: #e9ecef" disabled>
</div>
<div class="mb-3">
<label for="inputKelas" class="form-label">Kelas</label>
<input type="text" class="form-control" id="inputKelas" style="background-color: #e9ecef" disabled>
</div>
<div class="mb-3">
<label for="inputPenumpang" class="form-label">Jumlah penumpang</label>
<input type="text" class="form-control" id="inputPenumpang" style="background-color: #e9ecef" disabled>
</div>
</th>
</tr>
</tbody>
<table class="table table-bordered">
<p><b>Penumpang</b></p>
<thead>
<tr bgcolor="#8e8eff">
<th scope="col">No</th>
<th scope="col">Nama</th>
<th scope="col">Nik</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>
<input type="Nama" class="form-control" id="inputNama">
</td>
<td><input type="IdKTP" class="form-control" id="inputKtp"></td>
</tr>
<tr>
<th scope="row">3</th>
<td>
<input type="Nama" class="form-control" id="inputNama">
</td>
<td><input type="IdKTP" class="form-control" id="inputKtp"></td>
</tr>
</tbody>
</table>
<a href="checkout" class="btn btn-success">checkout</a>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php echo $this->include('Detail/header'); ?>
<?php echo $this->include('Detail/navbar'); ?>
<?= $this->renderSection('content'); ?>
<?php echo $this->include('Detail/footer'); ?>
<file_sep><nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href<?=base_url("") ?>/="#"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-link" href="<?=base_url("") ?>/index.php">Pesawat</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?=base_url("") ?>/detail_kereta">Kereta</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?=base_url("") ?>/detail_kapal">Kapal <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?=base_url("") ?>/detail_bus">Bus</a>
</li>
<!-- <li class="nav-item">
<a class="nav-link" href="<?=base_url("/auth") ?>/login">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?=base_url("/auth") ?>/register">Register</a>
</li> -->
<li class="nav-item">
<a class="nav-link" href="<?=base_url("/auth") ?>/logout">Logout</a></li>
</ul>
</div>
</nav><file_sep><?php namespace App\Controllers;
use App\Models\TiketModel;
class Dashboard extends BaseController
{
public function index()
{
$model = new TiketModel();
$data = $model->findAll();
return view("dashboard", ['data' => $data]);
}
//--------------------------------------------------------------------
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Travel</title>
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<!-- Tempusdominus Bootstrap 4 -->
<link rel="stylesheet" href="plugins/tempusdominus-bootstrap-4/css/tempusdominus-bootstrap-4.min.css">
<!-- iCheck -->
<link rel="stylesheet" href="plugins/icheck-bootstrap/icheck-bootstrap.min.css">
<!-- JQVMap -->
<link rel="stylesheet" href="plugins/jqvmap/jqvmap.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/adminlte.min.css">
<!-- overlayScrollbars -->
<link rel="stylesheet" href="plugins/overlayScrollbars/css/OverlayScrollbars.min.css">
<!-- Daterange picker -->
<link rel="stylesheet" href="plugins/daterangepicker/daterangepicker.css">
<!-- summernote -->
<link rel="stylesheet" href="plugins/summernote/summernote-bs4.min.css">
</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
<!-- Main Sidebar Container -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
<!-- Brand Logo -->
<a class="brand-link">
<span class="brand-text font-weight-light">Tiket Travel</span>
</a>
<!-- Sidebar -->
<div class="sidebar">
<!-- Sidebar Menu -->
<nav class="mt-2">
<ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false">
<!-- Add icons to the links using the .nav-icon class
with font-awesome or any other icon font library -->
<li class="nav-item menu-open">
<a href="admin" class="nav-link">
<i class="nav-icon fas fa-tachometer-alt"></i>
<p>
Dashboard
</p>
</a>
</li>
<li class="nav-item">
<a href="data_tiket" class="nav-link active">
<i class="nav-icon fas fa-copy"></i>
<p>
Data Tiket
</p>
</a>
</ul>
</nav>
</div>
</aside>
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
</div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<div class="jumbotron">
<?php if(isset($validation)):?>
<div class="alert alert-danger"><?= $validation->listErrors() ?></div>
<?php endif;?>
<div class="container">
<h1 class="mt-2">Tambah Data Tiket</h1>
<form action="<?=base_url("")?>\tambah\save" method="post">
<div class="row mb-3">
<label for="inputPesawat" class="col-sm-1 col-form-label">No</label>
<div class="col-sm-6">
<input type="jenis pesawat" class="form-control" id="notiket" name="notiket">
</div>
</div>
<div class="row mb-3">
<label for="inputPesawat" class="col-sm-1 col-form-label">Penyedia</label>
<div class="col-sm-6">
<input type="jenis pesawat" class="form-control" id="inputPesawat" name="inputPesawat">
</div>
</div>
<div class="row mb-3">
<label for="inputWaktu" class="col-sm-1 col-form-label">Waktu</label>
<div class="col-sm-6">
<input type="Date" class="form-control" id="inputWaktu" name="inputWaktu">
</div>
</div>
<div class="row mb-3">
<label for="inputJurusan" class="col-sm-1 col-form-label">Jurusan</label>
<div class="col-sm-6">
<input type="Jurusan" class="form-control" id="inputJurusan" name="inputJurusan">
</div>
</div>
<div class="row mb-3">
<label for="inputKelas" class="col-sm-1 col-form-label">Kelas</label>
<div class="col-sm-6">
<input type="Kelas" class="form-control" id="inputKelas" name="inputKelas">
</div>
</div>
<div class="row mb-3">
<label for="inputPenumpang" class="col-sm-1 col-form-label">Harga Tiket</label>
<div class="col-sm-6">
<input type="Jumlah Penumpang" class="form-control" id="inputPenumpang" name="inputPenumpang">
</div>
</div>
<div class="row mb-3">
<label for="inputTotal" class="col-sm-1 col-form-label">Kursi</label>
<div class="col-sm-6">
<input type="Total Hrga" class="form-control" id="inputTotal" name="inputTotal">
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Tambah</button>
</form>
<div>
<!-- <a href="data_tiket" class="btn btn-success">Tambah</a> -->
<a href="data_tiket" class="btn btn-success">Kembali</a>
</div>
</div>
</div>
</div>
</section>
</div>
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<!-- /.control-sidebar -->
</div>
<!-- ./wrapper -->
<!-- jQuery -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- ChartJS -->
<script src="plugins/chart.js/Chart.min.js"></script>
<!-- Sparkline -->
<script src="plugins/sparklines/sparkline.js"></script>
<!-- JQVMap -->
<script src="plugins/jqvmap/jquery.vmap.min.js"></script>
<script src="plugins/jqvmap/maps/jquery.vmap.usa.js"></script>
<!-- jQuery Knob Chart -->
<script src="plugins/jquery-knob/jquery.knob.min.js"></script>
<!-- daterangepicker -->
<script src="plugins/moment/moment.min.js"></script>
<script src="plugins/daterangepicker/daterangepicker.js"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="plugins/tempusdominus-bootstrap-4/js/tempusdominus-bootstrap-4.min.js"></script>
<!-- Summernote -->
<script src="plugins/summernote/summernote-bs4.min.js"></script>
<!-- overlayScrollbars -->
<script src="plugins/overlayScrollbars/js/jquery.overlayScrollbars.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="dist/js/demo.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="dist/js/pages/dashboard.js"></script>
</body>
</html>
<file_sep><?php namespace App\Controllers;
class Cetak extends BaseController
{
public function index()
{
return view('cetak');
}
//--------------------------------------------------------------------
}<file_sep><?php namespace App\Controllers;
class Cek extends BaseController
{
public function index()
{
return view('cek');
}
//--------------------------------------------------------------------
}<file_sep>
<?= $this->extend('User/template'); ?>
<?= $this->section('content'); ?>
<!-- header-section-starts -->
<div class="header">
<div class="top-header">
<div class="logo">
<p>TIKET TRAVEL</p>
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="footer">
<div class="product-list-container">
<div class="product-list-title">
<span> Hey, Kamu </span>
<br>
<span class="bold-title"> Mau Kemana?</span>
</div>
<div class="product-list-content">
<div class="col-md-3">
<div class="product-box active" tabindex="-1">
<div class="product-logo">
<a href="index.php">
<img src="https://s-light.tiket.photos/t/01E25EBZS3W0FY9GTG6C42E1SE/original/vertical/2020/12/17/db5f8398-5b3f-46ea-974b-6ec2e27434a3-1608204389521-8431fc3743b2bc5282d5e90d589a1a01.png" alt="Pesawat" height="56" width="76">
<div class="active-product"></div>
</a>
</div>
<span class="product-label">Pesawat</span>
</div>
</div>
<div class="col-md-3">
<a href="detail_kereta">
<div class="product-box active" tabindex="-1">
<div class="product-logo">
<img src="https://s-light.tiket.photos/t/01E25EBZS3W0FY9GTG6C42E1SE/original/vertical/2020/12/17/10f6f8c5-bc53-4199-afc4-cd4555eb3f24-1608204459625-52651b070043c8e97b9155dd0f48d8e0.png" alt="Kereta Api" height="56" width="76">
</div>
<span class="product-label">Kereta Api</span>
</div>
</a>
</div>
<div class="col-md-3">
<a href="detail_kapal">
<div class="product-box active" tabindex="-1">
<div class="product-logo">
<img src="images/kapal.png" alt="mobil" height="56" width="76">
</div>
<span class="product-label">Kapal</span>
</div>
</a>
</div>
<div class="col-md-3">
<a href="detail_bus">
<div class="product-box active" tabindex="-1">
<div class="product-logo">
<img src="/images/bus.png" alt="bus" height="56" width="76">
</div>
<span class="product-label">Bus</span>
</div>
</a>
</div>
</div>
</div>
<div class="top-main">
<div class="card-group">
<div class="row"><center>
<span class="product-form-subtitle">Cek Ketersediaan Tiket Disini</span>
</center>
</div>
<center>
<div class="row">
<div class="col-md-3">
<div class="card" style="width: 35rem;"><div class="jumbotron" >
<div class="widget-input-container">
<div class="form-group row">
<label for="tanggal" class="col-sm-2 col-form-label">Tanggal</label>
<div class="col-sm-5">
<input type="Date" class="form-control" id="tanggal" name="tanggal" value="<?= old('tanggal') ?>">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card" style="width: 35rem;"><div class="jumbotron" >
<div class="widget-input-container">
<div class="form-group row">
<label for="jam" class="col-sm-2 col-form-label">Jam</label>
<div class="col-sm-5">
<input type="Time" class="form-control" id="jam" name="jam" value="<?= old('jam') ?>">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card" style="width: 35rem;"><div class="jumbotron" >
<div class="widget-input-container">
<div class="form-group row">
<label for="jalur" class="col-sm-2 col-form-label">Kelas Kabin</label>
<div class="col-sm-5">
<select class="form-control" aria-label=".form-select-lg example">
<option selected>pilih</option>
<option value="1">Ekonomi</option>
<option value="2">Premium Ekonomi</option>
<option value="3">Bisnis</option>
<option value="3">First</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="card" style="width: 35rem;"><div class="jumbotron" >
<div class="widget-input-container">
<div class="form-group row">
<label for="kursi" class="col-sm-2 col-form-label">Jumlah Kursi</label>
<div class="col-sm-5">
<input type="text" class="control" id="kursi" name="kursi" value="<?= old('kursi') ?>">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4">
<center>
<a href="cek">CEK TIKET</a>
</center>
</div>
</div>
</center>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?>
<file_sep><?php namespace App\Controllers;
use App\Models\UserModel;
class Auth extends BaseController
{
public function login()
{
if(session()->get('logged_in')){
return redirect()->to('/dashboard');
}else{
helper(['form']);
return view("auth/login");
}
}
public function check()
{
$session = session();
$model = new UserModel();
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$data = $model->where('user_email', $email)->first();
if($data){
$pass = $data['user_password'];
$verify_pass = password_verify($password, $pass);
if($verify_pass){
$ses_data = [
'user_id' => $data['user_id'],
'user_level' => $data['user_level'],
'user_name' => $data['user_name'],
'user_email' => $data['user_email'],
'logged_in' => TRUE
];
$session->set($ses_data);
if($data['user_level'] == 1){
return redirect()->to('/admin');
} else {
return redirect()->to('/dashboard');
}
}else{
$session->setFlashdata('msg', 'Wrong Password');
return redirect()->to('/auth/login');
}
}else{
$session->setFlashdata('msg', 'Email not Found');
return redirect()->to('/auth/login');
}
}
public function register()
{
if(session()->get('logged_in')){
return redirect()->to('/');
}else{
//include helper form
helper(['form']);
$data = [];
return view("auth/register");
}
}
public function save()
{
//include helper form
helper(['form']);
//set rules validation form
$rules = [
'name' => 'required|min_length[3]|max_length[20]',
'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[users.user_email]',
'password' => '<PASSWORD>]',
'confpassword' => '<PASSWORD>]'
];
if($this->validate($rules)){
$model = new UserModel();
$data = [
'user_name' => $this->request->getVar('name'),
'user_email' => $this->request->getVar('email'),
'user_password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
];
$model->save($data);
return redirect()->to('/auth/login');
}else{
$data['validation'] = $this->validator;
echo view('/auth/register', $data);
}
}
//--------------------------------------------------------------------
public function logout()
{
session()->destroy();
return redirect()->to('/auth/login');
}
}<file_sep>
<?= $this->extend('detail/template'); ?>
<?= $this->section('content'); ?>
<!-- header-section-starts -->
<div class="footer-main">
<div class="container">
<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img src="images/kereta.jpg" class="d-block w-100" alt="kereta" width="500px" height="500px">
</div>
<div class="carousel-item">
<img src="images/kereta1.jpg" class="d-block w-100" alt="travel" width="500px" height="500px">
</div>
<div class="carousel-item">
<img src="images/kereta2.jpg" class="d-block w-100" alt="travel" width="500px" height="500px">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
<div class="footer">
<div class="product-list-container">
<img src="https://s-light.tiket.photos/t/01E25EBZS3W0FY9GTG6C42E1SE/original/vertical/2020/12/17/10f6f8c5-bc53-4199-afc4-cd4555eb3f24-1608204459625-52651b070043c8e97b9155dd0f48d8e0.png" alt="Kereta Api" height="56" width="76">
<div class="product-list-title">
<br>
<span class="bold-title"> Cek Ketersediaan Tiket Disini</span>
</div>
</div>
<div class="top-main">
<div class="card-group">
<div class="row">
<div class="col-md-3">
<div class="container">
<div class="widget-input-container">
<div class="form-group row">
<label for="tanggal" class="col-sm-2 col-form-label">Tanggal</label>
<div class="col-sm-5">
<input type="Date" class="form-control" id="tanggal" name="tanggal" value="<?= old('tanggal') ?>">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container">
<div class="widget-input-container">
<div class="form-group row">
<label for="jam" class="col-sm-2 col-form-label">Jam</label>
<div class="col-sm-5">
<input type="Time" class="form-control" id="jam" name="jam" value="<?= old('jam') ?>">
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container">
<div class="widget-input-container">
<div class="form-group row">
<label for="jalur" class="col-sm-2 col-form-label">Kelas</label>
<div class="col-sm-5">
<select class="form-control" aria-label=".form-select-lg example">
<option selected>pilih</option>
<option value="1">Eksekutif</option>
<option value="2">Ekonomi</option>
<option value="3">Bisnis</option>
<option value="3">Premium</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3">
<div class="container">
<div class="widget-input-container">
<div class="form-group row">
<label for="kursi" class="col-sm-2 col-form-label">jumlah penumpang</label>
<div class="col-sm-5">
<input type="text" class="control" id="kursi" name="kursi" value="<?= old('kursi') ?>">
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4">
<center>
<a href="cek">CEK TIKET</a>
</center>
</div>
</div>
</div>
</div>
</div>
<?= $this->endSection(); ?>
<file_sep><?= $this->extend('user/template'); ?>
<?= $this->section('content'); ?>
<div class="buttom">
<h1>TIKET TRAVEL</h1>
<span>Cek Dan Pesan Tiket Anda Disini</span>
<br>
<br>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/home" tabindex="-1" aria-disabled="true">Pesawat</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/detail_kereta" tabindex="-1" aria-disabled="true">Kereta</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/detail_kapal" tabindex="-1" aria-disabled="true">Kapal</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/detail_bus" tabindex="-1" aria-disabled="true">Bus</a>
<!-- </li>
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/auth/login" tabindex="-1" aria-disabled="true">Login</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/auth/register" tabindex="-1" aria-disabled="true">Register</a>
</li> -->
</li>
<li class="nav-item">
<a class="nav-link disabled" href="<?= base_url("") ?>/auth/logout" tabindex="-1" aria-disabled="true">Logout</a>
</li>
</ul>
</div>
<div class="jumbotron">
<div class="container">
<table class="table table-bordered">
<thead>
<tr bgcolor="#8e8eff">
<th scope="col">No</th>
<th scope="col">Penyedia</th>
<th scope="col">Waktu</th>
<th scope="col">Jurusan</th>
<th scope="col">Kelas</th>
<th scope="col">Harga Tiket</th>
<th scope="col">Kursi</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><a href="<?= base_url("") ?>/pesan" class="btn btn-success">Pilih</a></td>
</tr>
</tbody>
</table>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php namespace App\Controllers;
use App\Models\TiketModel;
class Tambah extends BaseController
{
public function index()
{
return view("tambah");
}
public function save()
{
helper(['form']);
$rules = [
'notiket' => 'required',
'inputPesawat' => 'required',
'inputWaktu' => 'required',
'inputJurusan' => 'required',
'inputKelas' => 'required',
'inputPenumpang' => 'required',
'inputTotal' => 'required'
];
if($this->validate($rules)){
$model = new TiketModel();
$data = [
'id' => $this->request->getVar('notiket'),
'penyedia' => $this->request->getVar('inputPesawat'),
'waktu' => $this->request->getVar('inputWaktu'),
'jurusan' => $this->request->getVar('inputJurusan'),
'kelas' => $this->request->getVar('inputKelas'),
'harga' => $this->request->getVar('inputPenumpang'),
'kursi' => $this->request->getVar('inputTotal')
];
$model->insert($data);
return redirect()->to('/data_tiket');
}else{
$data['validation'] = $this->validator;
echo view('/tambah', $data);
}
}
//--------------------------------------------------------------------
}<file_sep><?php namespace App\Controllers;
class Checkout extends BaseController
{
public function index()
{
return view('checkout');
}
//--------------------------------------------------------------------
}<file_sep><?= $this->extend('user/template'); ?>
<?= $this->section('content'); ?>
<div class="buttom">
<h1>TIKET TRAVEL</h1>
<span>Cek Dan Pesan Tiket Anda Disini</span>
</div>
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link disabled" href="home" tabindex="-1" aria-disabled="true">Pesawat</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kereta" tabindex="-1" aria-disabled="true">Kereta</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_kapal" tabindex="-1" aria-disabled="true">Kapal</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="detail_bus" tabindex="-1" aria-disabled="true">Bus</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/login" tabindex="-1" aria-disabled="true">Login</a>
</li>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="auth/register" tabindex="-1" aria-disabled="true">Register</a>
</li>
</ul>
<div class="jumbotron">
<div class="container">
<div class="col-lg-3 col-6">
<div class="small-box bg-success">
<center>
<img src="images/bri.png" width="200px">
<br>
<br>
<span><font color="blue"> No.Rekening : 5951-01-014122-xx-x </font></span>
<br>
<span> <font color="blue">Atas nama : Tiket Travel </font></span>
</center>
</div>
</div>
<div class="col-lg-3 col-6">
<div class="small-box bg-success">
<center>
<img src="images/bca.png" width="200px">
<br>
<br>
<span><font color="blue"> No.Rekening : 5220304xxx </font></span>
<br>
<span> <font color="blue">Atas nama : Tiket Travel </font></span>
</center>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr bgcolor="#8e8eff">
<th scope="col">No</th>
<th scope="col">Nomor Booking</th>
<th scope="col">Penyedia</th>
<th scope="col">Waktu</th>
<th scope="col">Pemesan</th>
<th scope="col">Jumlah Penumpang</th>
<th scope="col">Total Harga</th>
<th scope="col">Status Booking</th>
<th scope="col">Aksi</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row"></th>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<a href="bayar" class="btn btn-success">Bayar</a>
<a href="" class="btn btn-success">Batal</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<?= $this->endSection(); ?><file_sep><?php namespace App\Controllers;
class Home extends BaseController
{
public function index()
{
if(!session()->get('logged_in')){
return redirect()->to('/auth/login');
} else {
return view('home');
}
}
//--------------------------------------------------------------------
}
<file_sep><?php namespace App\Models;
use CodeIgniter\Model;
class TiketModel extends Model{
protected $table = 'tiket';
protected $primary = 'id';
protected $allowedFields = ['id', 'penyedia', 'waktu','jurusan','kelas','harga', 'kursi'];
}<file_sep><?php namespace App\Controllers;
class Detail_Bayar extends BaseController
{
public function index()
{
return view('detail_bayar');
}
//--------------------------------------------------------------------
} | bc976e2fd352863c2d0b561fc4ef2dc96f18ad51 | [
"SQL",
"PHP"
] | 26 | PHP | sucihikmawati/YGen-TiketTravel | 5cde61b0c230701a8c5c7e43842b1677f61c0164 | d7efb7cd91434e4cd62ebd972236d4a2c3716e0c | |
refs/heads/master | <file_sep><?php
namespace App\Http\Controllers;
use App\Models\Clothing;
use Illuminate\Http\Request;
class ClothingController extends Controller
{
public function index()
{
$clothings = Clothing::latest()->get();
return view('admin/index', [
'clothings' => $clothings]);
}
public function order(Request $request)
{
if ($request->isMethod('get'))
return view('create');
elseif ($request->isMethod('post')) {
$rules = [
'name' => 'required',
'material' => 'nullable|sometimes',
'color' => 'required',
'size' => 'required',
'address' => 'required',
'gender' => 'required',
'phone' => 'required',
'email' => 'required',
'image' => 'nullable|sometimes|image|mimes:jpeg,bmp,png,jpg,svg|max:500',
];
$clothing = new Clothing();
$clothing->material = request('material');
$clothing->color = request('color');
$clothing->address = request('address');
$clothing->name = request('name');
$clothing->gender = request('gender');
$clothing->size = request('size');
$clothing->email = request('email');
$clothing->phone = request('phone');
$clothing->image = '';
if ($request->hasfile('image')) {
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
$filename = $request->file('image')->getClientOriginalName();
$file->move('uploads/avatars', $filename);
$clothing->image = $filename;
}
$clothing->save();
return redirect('/')->with('success', 'Thanks for your order, you will be notified soon');
}
}
public function showa($id)
{
$clothing = Clothing::findOrFail($id);
return view('admin/show', ['clothing' => $clothing]);
}
public function destroy($id)
{
$clothing = Clothing::findOrFail($id);
$clothing->delete();
return redirect('/clothings');
}
public function edit($id)
{
$clothing = Clothing::findOrFail($id);
return view('clothings.edit', ['clothing' => $clothing]);
}
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'phone' => 'required',
'gender' => 'required',
'date' => 'required',
'material' => 'required',
'color' => 'required',
'style' => 'required',
'size' => 'required',
'additionaldetails' => 'required'
]);
$clothing = Clothing::find($id);
$clothing->material = request('material');
$clothing->color = request('color');
$clothing->style = request('style');
$clothing->name = request('name');
$clothing->gender = request('gender');
$clothing->date = request('date');
$clothing->size = request('size');
$clothing->email = request('email');
$clothing->phone = request('phone');
$clothing->additionaldetails = request('additionaldetails');
$clothing->save();
return redirect('/')->with('mssg', 'Update Successful');
}
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Sep 30, 2020 at 10:52 AM
-- Server version: 10.4.10-MariaDB
-- PHP Version: 7.3.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `clothing`
--
-- --------------------------------------------------------
--
-- Table structure for table `clothings`
--
DROP TABLE IF EXISTS `clothings`;
CREATE TABLE IF NOT EXISTS `clothings` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`material` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`color` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`gender` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`size` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`image` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `clothings`
--
INSERT INTO `clothings` (`id`, `material`, `color`, `name`, `gender`, `size`, `email`, `phone`, `image`, `address`, `created_at`, `updated_at`) VALUES
(1, 'Irish', 'Blue', '<NAME>', 'Male', '19, 20, 42, 36', '<EMAIL>', '08039093831', 'IMG_20190105_023001_361.JPG.jpg', 'Ran Road', '2020-09-29 15:36:00', '2020-09-29 15:36:00'),
(2, 'Irish', 'Brown', '<NAME>', 'Male', '19, 20, 42, 36', '<EMAIL>', '08036474862', 'IMG_20190114_041446_679.JPG.jpg', '<NAME>', '2020-09-29 20:22:45', '2020-09-29 20:22:45');
-- --------------------------------------------------------
--
-- Table structure for table `failed_jobs`
--
DROP TABLE IF EXISTS `failed_jobs`;
CREATE TABLE IF NOT EXISTS `failed_jobs` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`connection` text COLLATE utf8mb4_unicode_ci NOT NULL,
`queue` text COLLATE utf8mb4_unicode_ci NOT NULL,
`payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`failed_at` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `fromgallery`
--
DROP TABLE IF EXISTS `fromgallery`;
CREATE TABLE IF NOT EXISTS `fromgallery` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`galleries_id` int(11) NOT NULL,
`material` varchar(255) DEFAULT NULL,
`color` varchar(255) NOT NULL,
`name` varchar(255) NOT NULL,
`size` varchar(255) NOT NULL,
`gender` varchar(60) NOT NULL,
`address` varchar(255) NOT NULL,
`email` varchar(150) NOT NULL,
`phone` varchar(100) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `galleries`
--
DROP TABLE IF EXISTS `galleries`;
CREATE TABLE IF NOT EXISTS `galleries` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`material` varchar(200) NOT NULL,
`style` varchar(200) DEFAULT NULL,
`color` varchar(200) NOT NULL,
`image2` varchar(200) DEFAULT NULL,
`price` varchar(150) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `galleries`
--
INSERT INTO `galleries` (`id`, `material`, `style`, `color`, `image2`, `price`, `created_at`, `updated_at`) VALUES
(1, 'Cashmire', 'South South', 'Blue', 'IMG_20190105_023001_361.JPG.jpg', '2500', '2020-09-27 18:14:40', '2020-09-27 18:14:40'),
(2, 'Cashmire', 'South West', 'Green', 'BILLIE-EILISH.jpg', '3000', '2020-09-28 03:59:28', '2020-09-28 03:59:28'),
(3, 'Irish', 'Half Jumper', 'Brown', 'IMG_20190114_041403_325.JPG.jpg', '5000', '2020-09-28 04:02:12', '2020-09-28 04:02:12'),
(4, 'Plain', 'Jumper', 'White', 'IMG_20190114_041318_202.JPG.jpg', '6000', '2020-09-28 04:38:02', '2020-09-28 04:38:02');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
DROP TABLE IF EXISTS `migrations`;
CREATE TABLE IF NOT EXISTS `migrations` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2019_08_19_000000_create_failed_jobs_table', 1),
(3, '2020_03_23_100522_create_clothings_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usertype` int(1) NOT NULL DEFAULT 0,
`fullname` varchar(200) NOT NULL,
`phone` varchar(20) NOT NULL,
`email` varchar(160) NOT NULL,
`password` varchar(100) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime NOT NULL,
`active` int(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `phone` (`phone`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `usertype`, `fullname`, `phone`, `email`, `password`, `created_at`, `updated_at`, `active`) VALUES
(1, 1, '<NAME>', '08039093831', '<EMAIL>', '<PASSWORD>', '2020-09-27 19:36:38', '2020-09-27 19:36:38', 1);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Session;
class BaseController extends Controller
{
public function __construct()
{
}
public function dologout(Request $request)
{
Session()->flush();
return redirect('/');
}
protected function isLoggedIn()
{
$user = Session::get('logged_user');
if (!isset($user->id)) {
// Session::flash('warning','Please log in to proceed!');
return false;
} else {
return true;
}
}
}
<file_sep><?php
use App\Http\Controllers\ClothingController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\GalleryController;
use App\Http\Controllers\SigninController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::match(['get', 'post'], '/signin', [SigninController::class, 'index']);
Route::match(['get', 'post'], 'gallery', [GalleryController::class, 'gallery']);
Route::match(['get', 'post'], 'admin/creategallery', [GalleryController::class, 'creategallery']);
Route::match(['get', 'post'], '/clothings', [ClothingController::class, 'index']);
Route::match(['get', 'post'], '/order', [ClothingController::class, 'order']);
Route::get('/{id}', [ClothingController::class, 'show']);
Route::get('a/{id}', [ClothingController::class, 'showa']);
Route::match(['get', 'post'], '/register', [SigninController::class, 'register']);
Route::get('/{id}', [GalleryController::class, 'show']);
Route::match(['get', 'post'], '/orderg', [GalleryController::class, 'orderg']);
Route::group(array('prefix' => 'admin'), function () {
Route::get('/dashboard', [DashboardController::class, 'index']);
Route::get('/logout', [DashboardController::class, 'logout']);
Route::get('/{id}', [ClothingController::class, 'show']);
Route::match(['get', 'post'], 'admin/creategallery', [GalleryController::class, 'creategallery']);
Route::match(['get', 'post'], '/changepassword', [ProfileController::class, 'changepassword']);
Route::match(['get', 'post'], '/updateprofile', [ProfileController::class, 'updateprofile']);
});
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Fgallery;
use App\Models\Gallery;
use Illuminate\Http\Request;
class GalleryController extends BaseController
{
public function __construct()
{
}
public function gallery(Request $request)
{
$gallery = Gallery::all();
return view('gallery', ['gallery' => $gallery]);
}
public function creategallery(Request $request)
{
if ($request->isMethod('get'))
return view('admin/creategallery');
elseif ($request->isMethod('post')) {
$rules = [
'material' => 'required',
'style' => 'nullable|sometimes',
'color' => 'required',
'price' => 'required',
'image2' => 'nullable|sometimes|image|mimes:jpeg,bmp,png,jpg,svg|max:500',
];
$gallery = new Gallery();
$gallery->material = request('material');
$gallery->style = request('style');
$gallery->color = request('color');
$gallery->price = request('price');
$gallery->image2 = '';
if ($request->hasfile('image2')) {
$file = $request->file('image2');
$extension = $file->getClientOriginalExtension();
$filename = $request->file('image2')->getClientOriginalName();
$file->move('uploads/avatars', $filename);
$gallery->image2 = $filename;
}
$gallery->save();
return redirect()->back()->with('success', 'Style Successfuly uploaded');
}
}
public function orderg(Request $request)
{
// storing a review
$clothing = new Fgallery();
$clothing->material = request('material');
$clothing->galleries_id = request('pid');
$clothing->color = request('color');
$clothing->address = request('address');
$clothing->name = request('name');
$clothing->gender = request('gender');
$clothing->size = request('size');
$clothing->email = request('email');
$clothing->phone = request('phone');
$clothing->save();
return redirect('/')->with('success', 'Thanks for your order, you will be notified soon');
}
public function show($id)
{
$gallery = Gallery::findOrFail($id);
return view('show', ['gallery' => $gallery, 'c' => $id]);
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
protected $table = 'galleries';
public function orderg()
{
return $this->belongsToMany('App\Model\Fgallery');
}
}
<file_sep><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Clothing extends Model
{
protected $table = 'clothings';
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Models\Users;
use Illuminate\Http\Request;
use Session;
class SigninController extends BaseController
{
public function index(Request $request)
{
if ($request->isMethod('get'))
return view('signin');
elseif ($request->isMethod('post')) {
$rules = [
'email' => 'required',
'password' => '<PASSWORD>'
];
$validator = Validator()->make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()->withInput()->withErrors($validator);
} else {
$e = $request->email;
$p = md5($request->password);
$obj = Users::whereRaw("(email = '$e' OR phone = '$e') AND password = '$p'")->get();
if ($obj && count($obj) > 0) {
Session::put('logged_user', $obj[0]);
Session::save();
return redirect('admin/dashboard');
} else {
return redirect()->back()->with('error', 'Invalid login details. Please try again.');
}
}
}
}
public function register(Request $request)
{
// return view('faq');
if ($request->isMethod('get'))
return view('register');
elseif ($request->isMethod('post')) {
$rules = [
'fullname' => 'required',
'phone' => 'required|unique:users,phone',
'email' => 'required|email|unique:users,email',
'password' => '<PASSWORD>',
'cpassword' => '<PASSWORD>'
];
$passchecked = ($request->password !== $request->cpassword);
$validator = Validator()->make($request->all(), $rules);
if ($validator->fails() || $passchecked) {
if ($passchecked)
$validator->errors()->add('password', 'The password and confirm password must be the same');
return redirect()->back()->withInput()->withErrors($validator);
} else {
$obj = new Users;
$obj->usertype = 1;
$obj->active = 1;
$obj->fullname = $request->fullname;
$obj->phone = $request->phone;
$obj->email = $request->email;
$obj->password = md5($request->password);
// print_r($obj);exit;
if ($obj->save()) {
return redirect()->back()->with('success', 'Your account has been created successfully. Please signin to continue to your dashboard.');
} else {
return redirect()->back()->with('error', 'Invalid login details. Please try again.');
}
}
}
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class DashboardController extends BaseController
{
public function __construct()
{
}
public function index(Request $request)
{
if ($this->isLoggedIn()) {
return view("admin/dashboard");
} else {
return redirect('/')->with('warning', 'Please log in to proceed!');
}
}
public function logout(Request $request)
{
return $this->dologout($request);
}
}
| 34d819c071b23d9241b36e3f25890c08b3fa3525 | [
"SQL",
"PHP"
] | 9 | PHP | 243Galaxy/clothings | cdadaf39824f9b22fe2c5c822de0e136a31e921c | aea47d10a50290702051a50df9bd2cb2045868b1 | |
refs/heads/master | <file_sep>const download = require('./lib/download').download;
const slack = require('./lib/slack').slack;
const trim = require('./lib/trim').trim;
const { tweet, upload } = require('./lib/tweet');
const getVideos = require('./lib/video').getVideos;
module.exports = {
download,
slack,
trim,
tweet,
upload,
getVideos
};
<file_sep>require('dotenv').config();
const url = process.env.SLACK_INCOMING_WEBHOOK;
if (!url) {
console.error('Please set SLACK_INCOMING_WEBHOOK into .env');
}
exports.slack = function slack(text) {
return fetch(url, {
method: 'POST',
body: JSON.stringify({
username: 'youtube-to-twitter',
text
})
});
};
<file_sep>const { timeline, isDupulicated } = require('./timeline');
require('dotenv').config();
const endpoint = 'https://www.googleapis.com/youtube/v3/playlistItems';
const key = process.env.YOUTUBE_DATA_API_KEY;
const playlist = process.env.YOUTUBE_PLAYLIST_ID;
async function getVideos(playlistId = playlist) {
const response = await fetch(
`${endpoint}?part=snippet,contentDetails,status&maxResults=50&playlistId=${playlistId}&key=${key}`,
{
headers: {
Referer: 'https://www.hackforplay.xyz/'
}
}
);
const json = await response.text();
const data = JSON.parse(json);
if (!response.ok) {
console.error(data.error);
throw new Error(data.error.message);
}
const tl = await timeline();
// 直近のツイートで紹介していない動画
const videos = [];
let notPublishedYet = 0;
let alreadyTweeted = 0;
for (const item of data.items) {
const {
snippet: { title },
contentDetails: { videoId, videoPublishedAt }
} = item;
if (!videoPublishedAt) {
notPublishedYet += 1;
continue; // not published yet
}
const url = `https://www.youtube.com/watch?v=${videoId}`;
if (isDupulicated(tl, url)) {
alreadyTweeted += 1;
continue; // already tweeted
}
videos.push({
title,
url
});
}
if (videos.length === 0) {
console.log(`fetched ${data.items.length}`);
console.log(`tweeted ${alreadyTweeted}`);
console.log(`waiting ${notPublishedYet}`);
throw new Error('No video found');
}
return videos;
}
exports.getVideos = getVideos;
<file_sep># YouTube to Twitter
Download video from youtube channel and upload it twitter.
## Install
> npm install --save youtube-to-twitter
## Example
See [server.js](server.js)
```javascript
const express = require('express');
const { download, trim, tweet, upload, video } = require('youtube-to-twitter');
const app = express();
app.get('/', async (req, res) => {
res.sendStatus(200);
main()
.then(console.log)
.catch(console.error);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listen on port ${port}`);
});
async function main() {
const start = parseInt(process.env.VIDEO_START, 10) || 0;
const duration = parseInt(process.env.VIDEO_DURATION, 10) || 30;
const { title, url } = await video();
const status =
title.replace(/【ハックフォープレイ実況】/, ' #HackforPlay') +
'\n\nつづきはこちら↓\n' +
url;
console.log('next tweet:\n', status);
const source = await download(url);
const output = await trim(source, start, start + duration);
const mediaId = await upload(output);
await tweet(mediaId, status);
}
```
<file_sep>const tmp = require('tmp');
const ytdl = require('ytdl-core');
const fs = require('fs');
function download(url) {
const filepath = tmp.tmpNameSync({ postfix: '.mp4' });
return new Promise((resolve, reject) => {
ytdl(url, {
filter: (format) =>
format.container === 'mp4' && format.qualityLabel === '720p'
})
.pipe(fs.createWriteStream(filepath))
.on('error', reject)
.on('close', () => {
console.log('download complete: ', filepath);
resolve(filepath);
});
});
}
exports.download = download;
<file_sep>const client = require('./tweet').client;
function timeline() {
return client.get('statuses/user_timeline', {
count: 200,
trim_user: true,
exclude_replies: true
});
}
exports.timeline = timeline;
function isDupulicated(timeline, url) {
for (const tweet of timeline) {
const {
entities: { urls }
} = tweet;
if (!Array.isArray(urls) || urls.length < 1) continue;
for (const { expanded_url } of urls) {
if (url === expanded_url) {
return true;
}
}
}
return false;
}
exports.isDupulicated = isDupulicated;
<file_sep>const express = require('express');
const fs = require('fs').promises;
const { download, slack, trim, tweet, upload, getVideos } = require('./index');
const app = express();
app.get('/', (req, res) => {
res.sendStatus(200);
});
app.get('/update', async (req, res) => {
res.sendStatus(200);
const dryRun = req.query.dryRun === 'true'; // ?dryRun=true でモード有効化
main({ dryRun }).then(console.log).catch(console.error);
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`listen on port ${port}`);
});
async function main({ dryRun = false }) {
const start = parseInt(process.env.VIDEO_START, 10) || 0;
const duration = parseInt(process.env.VIDEO_DURATION, 10) || 30;
let lastError = null; // ひとつもツイート出来なかった場合 Slack に通知する
try {
const videos = await getVideos();
videos.reverse().splice(10); // 古い順に最大10件までリトライ
// 直近で紹介していない動画を順番にダウンロードとアップロードを試みる
for (const { title, url } of videos) {
let mediaId = '';
try {
const source = await download(url);
const output = await trim(source, start, duration);
await fs.unlink(source);
mediaId = await upload(output);
await fs.unlink(output);
} catch (error) {
console.warn(error);
lastError = error; // エラーを保持して次へ
continue;
}
if (dryRun) {
return;
}
// アップロードに成功したのでツイートして終了
const status =
title.replace(/【ハックフォープレイ実況】/, '') +
'\n\nつづきはこちら↓\n' +
url;
console.log('next tweet:\n', status);
await tweet(mediaId, status);
return;
}
if (lastError) {
if (dryRun) {
console.error(lastError);
return;
}
throw lastError;
}
} catch (error) {
try {
await slack(error.message);
} catch (error) {
console.warn('Failed to send slack webhook!', error);
}
}
}
| 8797c1d7f00aaa5b4a74946798976a93577d0960 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | teramotodaiki/youtube-to-twitter | afab891c85aea317289c7dc064bde77c63295c7a | 03c80ab83b6d266d7472b5d226112cfe12e14ef9 | |
refs/heads/main | <file_sep>const trackerbtn = document.querySelector('.btn-tracker');
const input = document.querySelector('input');
const alerts = document.querySelector('.tracker-alerts-wrap');
const trackerHead = document.querySelector('.tracker-head');
const overlay = document.querySelector('.overlay')
const mapContainer = document.querySelector('.tracker-map');
const Api_Key = '<KEY>'
const domains = ['https://', 'http://', 'www.', 'https://www.', 'http://www.']
const token = '<KEY>'
function trackme(region, country, zone, provider){
const infowrap = document.querySelector('.tracker-info-wrap');
infowrap.style.transition = 'all 200ms ease-in-out';
const info = document.createElement('div');
info.classList.add('tracker-info');
info.classList.add('fade-in');
info.classList.remove('fade-out');
const ipaddress_wrap = document.createElement('div');
const ipaddress_div = document.createElement('div');
ipaddress_wrap.classList.add('tracker-container');
const ipaddress_head = document.createElement('p');
const ipaddress = document.createElement('p');
ipaddress.textContent = input.value;
ipaddress.style.maxWidth = '200%'
ipaddress.classList.add('tracker-content');
ipaddress_head.innerHTML = 'IP Address'
const ip_divider = document.createElement('span');
ip_divider.classList.add('divider');
ipaddress_div.appendChild(ipaddress_head)
ipaddress_div.appendChild(ipaddress);
ipaddress_wrap.appendChild(ipaddress_div);
ipaddress_wrap.appendChild(ip_divider)
info.appendChild(ipaddress_wrap);
const location_wrap = document.createElement('div');
const location_div = document.createElement('div');
location_wrap.classList.add('tracker-container');
const location_head = document.createElement('p');
const location = document.createElement('p');
location.textContent = region + ', ' + country;
location.classList.add('tracker-content');
location.style.maxWidth = '200%'
location_head.innerHTML = 'Location';
const location_divider = document.createElement('span');
location_divider.classList.add('divider');
location_div.appendChild(location_head)
location_div.appendChild(location);
location_wrap.appendChild(location_div);
location_wrap.appendChild(location_divider);
info.appendChild(location_wrap);
const timezone_wrap = document.createElement('div');
const timezone_div = document.createElement('div');
timezone_wrap.classList.add('tracker-container');
const timezone_head = document.createElement('p');
const timezone = document.createElement('p');
timezone.textContent = "UTC -" + zone;
timezone.classList.add('tracker-content');
timezone.style.paddingTop = '10%';
timezone.style.maxWidth = '200%';
timezone_head.innerHTML = 'Timezone';
const timezone_divider = document.createElement('span');
timezone_divider.classList.add('divider');
timezone_div.appendChild(timezone_head)
timezone_div.appendChild(timezone);
timezone_wrap.appendChild(timezone_div);
timezone_wrap.appendChild(timezone_divider);
info.appendChild(timezone_wrap);
const isp_div = document.createElement('div');
const isp_head = document.createElement('p');
const isp = document.createElement('p');
isp.textContent = provider;
isp.style.maxWidth = '200%';
isp.classList.add('tracker-content');
isp_head.innerHTML = 'ISP';
isp_div.appendChild(isp_head)
isp_div.appendChild(isp);
info.appendChild(isp_div);
const closer = document.createElement('button');
const closer_class = document.createElement('i');
closer_class.classList.add('fa');
closer_class.classList.add('fa-times');
closer.classList.add('closer');
closer.appendChild(closer_class);
info.appendChild(closer);
infowrap.appendChild(info);
closer.addEventListener('click', ()=>{
info.classList.remove('fade-in');
info.classList.add('fade-out');
setTimeout(()=>{
infowrap.removeChild(info);
}, 1000)
})
if (input.value.substr(0, 8) === domains[0] || input.value.substr(0, 7) === domains[1] || input.value.substr(0, 4) === domains[2] || input.value.substr(0, 12) === domains[3] || input.value.substr(0, 11) === domains[4]) {
ipaddress_head.innerHTML = 'Domain'
}
if(input.value.substr(0, 8) === domains[0]){
ipaddress.innerHTML = input.value.substring(8);
}
if (input.value.substr(0, 7) === domains[1]) {
ipaddress.innerHTML = input.value.substring(7);
}
if (input.value.substr(0, 4) === domains[2]) {
ipaddress.innerHTML = input.value.substring(4);
}
if (input.value.substr(0, 12) === domains[3]) {
ipaddress.innerHTML = input.value.substring(12);
}
if (input.value.substr(0, 11) === domains[4]) {
ipaddress.innerHTML = input.value.substring(11);
}
}
const Api_URL = 'https://geo.ipify.org/api/v1?apiKey='
async function fetchUrl() {
const url = Api_URL+Api_Key+'&ipAddress='+input.value
const response = await fetch(url);
const data = await response.json();
trackme(data.location.region, data.location.country, data.location.timzone, data.isp)
if (data.ip === undefined) {
console.log(data.ip);
return
}
/*Script for Mapping */
// mapboxgl.accessToken = token;
// let map = new mapboxgl.Map({
// container: 'map',
// style: 'mapbox://styles/mapbox/streets-v11',
// zoom: 12,
// center: [data.location.lng, data.location.lat]
// });
// let geojson = [
// {
// type: 'FeatureCollection',
// features: [{
// type: 'Feature',
// geometry:{
// type: 'Point',
// coordinates: [data.location.lng, data.location.lat]
// },
// properties:{
// title: data.as.name,
// description: data.isp
// }
// }]
// }
// ];
// geojson.features.forEach(function(marker){
// let mark = document.createElement('div');
// mark.classList.add('marker');
// new mapboxgl.Marker(mark)
// .setLngLat(marker.geometry.coordinates)
// .setPopup(new mapboxgl.Popup({
// offset: 25
// }))
// .setHTML(`<h3>`+marker.properties.title+`</h3> <p>`+marker.properties.description+`</p>`)
// .addTo(map)
// })
}
function tracker() {
if (input.value==="" || input.value === null) {
input.classList.add('disappear');
trackerbtn.classList.add('disappear');
mapContainer.classList.add('disappear');
trackerHead.classList.add('enabled');
overlay.classList.add('enabled');
const alertOne = document.createElement('div');
const alertOneIcon = document.createElement('i');
const alertOneInfo = document.createElement('p');
const alertOneHead = document.createElement('h5');
const alertOneCta = document.createElement('button');
alertOne.classList.add('fade-in');
alertOneIcon.classList.add('fa');
alertOneIcon.classList.add('fa-warning');
alertOneHead.innerHTML = 'Trackdown says:'
alertOne.classList.add('tracker-alert');
alertOneInfo.innerHTML = 'Please enter the IP Address you want to track down.';
alertOneCta.innerHTML = 'Got it'
alertOneCta.classList.add('tracker-cta');
alertOne.appendChild(alertOneIcon);
alertOne.appendChild(alertOneHead);
alertOne.appendChild(alertOneInfo);
alertOne.appendChild(alertOneCta);
alerts.appendChild(alertOne);
alertOneCta.addEventListener('click', ()=>{
alertOne.classList.remove('fade-in');
alertOne.classList.add('fade-out');
setTimeout(()=>{
alerts.removeChild(alertOne);
}, 1000)
input.classList.remove('disappear');
trackerbtn.classList.remove('disappear');
mapContainer.classList.remove('disappear');
trackerHead.classList.remove('enabled');
overlay.classList.remove('enabled');
})
}
else if(input.value.substr(0, 8) !== domains[0] && input.value.substr(0, 7) !== domains[1] && input.value.substr(0, 4) !== domains[2] && input.value.substr(0, 12) !== domains[3] && input.value.substr(0, 11) !== domains[4]){
let checkip = /[.]/
if (checkip.test(input.value) === false) {
input.value = '';
input.classList.add('disappear');
trackerbtn.classList.add('disappear');
mapContainer.classList.add('disappear');
trackerHead.classList.add('enabled');
overlay.classList.add('enabled');
const alertTwo = document.createElement('div');
const alertTwoIcon = document.createElement('i');
const alertTwoInfo = document.createElement('p');
const alertTwoHead = document.createElement('h5');
const alertTwoCta = document.createElement('button');
alertTwo.classList.add('fade-in');
alertTwoIcon.classList.add('fa');
alertTwoIcon.classList.add('fa-warning');
alertTwoHead.innerHTML = 'Trackdown says:'
alertTwo.classList.add('tracker-alert');
alertTwoInfo.innerHTML = 'Please enter a correct IP Address.';
alertTwoCta.innerHTML = 'Got it'
alertTwoCta.classList.add('tracker-cta');
alertTwo.appendChild(alertTwoIcon);
alertTwo.appendChild(alertTwoHead);
alertTwo.appendChild(alertTwoInfo);
alertTwo.appendChild(alertTwoCta);
alerts.appendChild(alertTwo);
alertTwoCta.addEventListener('click', ()=>{
alertTwo.classList.remove('fade-in');
alertTwo.classList.add('fade-out');
setTimeout(()=>{
alerts.removeChild(alertTwo);
}, 1000)
input.classList.remove('disappear');
trackerbtn.classList.remove('disappear');
mapContainer.classList.remove('disappear');
trackerHead.classList.remove('enabled');
overlay.classList.remove('enabled');
})
}
else{
fetchUrl();
}
}
else{
fetchUrl();
}
}
trackerbtn.addEventListener('click', ()=>{
tracker();
mapContainer.classList.add('seemap')
});
input.addEventListener('keyup', event=>{
if (event.keyCode === 13) {
tracker();
mapContainer.classList.add('seemap')
}
})
| 1515dfecebea2983ced96b236e5966119b7c626c | [
"JavaScript"
] | 1 | JavaScript | milexpro/trackdown | 1e6ff59e2fd6d77d8b4b886ddace4fe2340448ec | cddd72ec26d6e355317ba78f3ae596da9ff1f027 | |
refs/heads/master | <repo_name>lighterletter/StockProduct<file_sep>/src/c4q/lighterletter/NumProduct.java
package c4q.lighterletter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by c4q-john on 11/16/15.
*/
public class NumProduct {
public static void main(String[] args) {
int[] array = {1,7,3,4};
System.out.println(get_products_of_all_ints_except_at_index(array).toString());
}
public static List<Integer> get_products_of_all_ints_except_at_index(int[] array){
int product = 1;
List<Integer> products = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++) {
for (int k = 0; k < array.length; k++) {
if (i!=k){
product *= array[k];
}
}
products.add(product);
product = 1;
}
return products;
}
}
/* Like the sea and the sand are continents. So are the blankets above my feet that cover me. Aware upon a single happenstance,
aware among a single goal. Survival. What are the goals that cover me? My thoughts and the keys they hold within. I feel that knowing them
can lead me to make the right choice.
*/
| 9ae283886229422c18fb8acf816dd76f065de4c0 | [
"Java"
] | 1 | Java | lighterletter/StockProduct | 3bab8c4bbcca846b6fa3a0b20058656f8cb0f7ca | b81bad360548249876de9aa670c9b1158e8b1fe9 | |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class scr_Clicking : MonoBehaviour
{
public Text counter;
public float counterNumber;
public float ammountPerClick == 1.0f;
// Update is called once per frame
void Update()
{
counter.text = counterNumber + " Cookies";
}
public void Clicked()
{
counterNumber += ammountPerClick
}
}
| 815809cb89f8f3d44e91d1a3b7dad256fc0d7e40 | [
"C#"
] | 1 | C# | Toastiin/CookieClicker | 0efe73a91b11a697cc503b7a36436b2d1a4ea235 | 4fbf9aef2d2933d460f20c4b7afd5a5207fa77d1 | |
refs/heads/main | <repo_name>joonhwan/nginx-multiple-react-with-router<file_sep>/clients/app/src/Home.js
export default function Home() {
return (
<div>
<h2>Home Page</h2>
<p>User App - Home</p>
</div>
);
}
<file_sep>/clients/app/src/App.js
import { Switch, Route, NavLink, Link } from "react-router-dom";
import "./App.css";
import Home from "./Home";
import About from "./About";
import NotFound from "./NotFound";
function App() {
return (
<div className="App">
<div>
<ul>
<li>
<NavLink to="/home">Home</NavLink>
</li>
<li>
<NavLink to="/about">About</NavLink>
</li>
<li>
<a href="/dashboard">Dashboard</a>
</li>
</ul>
</div>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/home" component={Home} />
<Route path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</div>
);
}
export default App;
<file_sep>/clients/dashboard/src/Manage.js
export default function Manage() {
return (
<div>
<h2>Manage Page</h2>
<p>Dashboard App - Manage</p>
</div>
);
}
<file_sep>/clients/dashboard/src/Settings.js
export default function Settings() {
return (
<div>
<h2>Settings Page</h2>
<p>Dashboard App - Settings</p>
</div>
);
}
<file_sep>/clients/dashboard/src/App.js
import { Route, Switch, Redirect, NavLink, Link } from "react-router-dom";
import "./App.css";
import Manage from "./Manage";
import Settings from "./Settings";
import NotFound from "./NotFound";
function App() {
return (
<div className="App">
<nav>
<ul>
<li>
<NavLink to="/manage">Manage</NavLink>
</li>
<li>
<NavLink to="/settings">Settings</NavLink>
</li>
<li>
<a href="/app">Return User App</a>
</li>
</ul>
</nav>
<Switch>
<Route path="/" exact>
<Redirect to={"/manage"} />
</Route>
<Route path="/manage" component={Manage} />
<Route path="/settings" component={Settings} />
<Route component={NotFound} />
</Switch>
</div>
);
}
export default App;
| 35e59e7e8c466969eb9c6bbb8fec7dfc57d2c3d4 | [
"JavaScript"
] | 5 | JavaScript | joonhwan/nginx-multiple-react-with-router | 30310d8054549a452b87b0f3df014568d8f88bd0 | 9596dd5dd2bebb0a25e4bc743f624a020a2d5e7a | |
refs/heads/master | <file_sep>package exprivia;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="dlfileentry")
public class Dlfileentry implements java.io.Serializable{
private long fileEntryId;
private String version;
private String uuid;
private Long groupId;
private Long companyId;
private Long userId;
private String userName;
private Date createDate;
private Date modifiedDate;
private Long classNameId;
private Long classPk;
private Long repositoryId;
private Long folderId;
private String treePath;
private String name;
private String extension;
private String mimeType;
private String title;
private String description;
private String extraSettings;
private Long fileEntryTypeId;
private Long size;
private Integer readCount;
private Long smallImageId;
private Long largeImageId;
private Long custom1imageId;
private Long custom2imageId;
private Byte manualCheckInRequired;
public Dlfileentry() {
}
public Dlfileentry(long fileEntryId) {
this.fileEntryId = fileEntryId;
}
public Dlfileentry(long fileEntryId, String uuid, Long groupId,
Long companyId, Long userId, String userName, Date createDate,
Date modifiedDate, Long classNameId, Long classPk,
Long repositoryId, Long folderId, String treePath, String name,
String extension, String mimeType, String title,
String description, String extraSettings, Long fileEntryTypeId,
Long size, Integer readCount, Long smallImageId, Long largeImageId,
Long custom1imageId, Long custom2imageId, Byte manualCheckInRequired) {
this.fileEntryId = fileEntryId;
this.uuid = uuid;
this.groupId = groupId;
this.companyId = companyId;
this.userId = userId;
this.userName = userName;
this.createDate = createDate;
this.modifiedDate = modifiedDate;
this.classNameId = classNameId;
this.classPk = classPk;
this.repositoryId = repositoryId;
this.folderId = folderId;
this.treePath = treePath;
this.name = name;
this.extension = extension;
this.mimeType = mimeType;
this.title = title;
this.description = description;
this.extraSettings = extraSettings;
this.fileEntryTypeId = fileEntryTypeId;
this.size = size;
this.readCount = readCount;
this.smallImageId = smallImageId;
this.largeImageId = largeImageId;
this.custom1imageId = custom1imageId;
this.custom2imageId = custom2imageId;
this.manualCheckInRequired = manualCheckInRequired;
}
@Id
@Column(name = "fileEntryId", unique = true)
public long getFileEntryId() {
return this.fileEntryId;
}
public void setFileEntryId(long fileEntryId) {
this.fileEntryId = fileEntryId;
}
@Column(name = "version", length = 75)
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
@Column(name = "uuid_", length = 75)
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Column(name = "groupId")
public Long getGroupId() {
return this.groupId;
}
public void setGroupId(Long groupId) {
this.groupId = groupId;
}
@Column(name = "companyId")
public Long getCompanyId() {
return this.companyId;
}
public void setCompanyId(Long companyId) {
this.companyId = companyId;
}
@Column(name = "userId")
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
@Column(name = "userName", length = 75)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "createDate", length = 19)
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "modifiedDate", length = 19)
public Date getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
@Column(name = "classNameId")
public Long getClassNameId() {
return this.classNameId;
}
public void setClassNameId(Long classNameId) {
this.classNameId = classNameId;
}
@Column(name = "classPK")
public Long getClassPk() {
return this.classPk;
}
public void setClassPk(Long classPk) {
this.classPk = classPk;
}
@Column(name = "repositoryId")
public Long getRepositoryId() {
return this.repositoryId;
}
public void setRepositoryId(Long repositoryId) {
this.repositoryId = repositoryId;
}
@Column(name = "folderId")
public Long getFolderId() {
return this.folderId;
}
public void setFolderId(Long folderId) {
this.folderId = folderId;
}
@Column(name = "treePath")
public String getTreePath() {
return this.treePath;
}
public void setTreePath(String treePath) {
this.treePath = treePath;
}
@Column(name = "name")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "extension", length = 75)
public String getExtension() {
return this.extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
@Column(name = "mimeType", length = 75)
public String getMimeType() {
return this.mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
@Column(name = "title")
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Column(name = "description")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "extraSettings")
public String getExtraSettings() {
return this.extraSettings;
}
public void setExtraSettings(String extraSettings) {
this.extraSettings = extraSettings;
}
@Column(name = "fileEntryTypeId")
public Long getFileEntryTypeId() {
return this.fileEntryTypeId;
}
public void setFileEntryTypeId(Long fileEntryTypeId) {
this.fileEntryTypeId = fileEntryTypeId;
}
@Column(name = "size_")
public Long getSize() {
return this.size;
}
public void setSize(Long size) {
this.size = size;
}
@Column(name = "readCount")
public Integer getReadCount() {
return this.readCount;
}
public void setReadCount(Integer readCount) {
this.readCount = readCount;
}
@Column(name = "smallImageId")
public Long getSmallImageId() {
return this.smallImageId;
}
public void setSmallImageId(Long smallImageId) {
this.smallImageId = smallImageId;
}
@Column(name = "largeImageId")
public Long getLargeImageId() {
return this.largeImageId;
}
public void setLargeImageId(Long largeImageId) {
this.largeImageId = largeImageId;
}
@Column(name = "custom1ImageId")
public Long getCustom1imageId() {
return this.custom1imageId;
}
public void setCustom1imageId(Long custom1imageId) {
this.custom1imageId = custom1imageId;
}
@Column(name = "custom2ImageId")
public Long getCustom2imageId() {
return this.custom2imageId;
}
public void setCustom2imageId(Long custom2imageId) {
this.custom2imageId = custom2imageId;
}
@Column(name = "manualCheckInRequired")
public Byte getManualCheckInRequired() {
return this.manualCheckInRequired;
}
public void setManualCheckInRequired(Byte manualCheckInRequired) {
this.manualCheckInRequired = manualCheckInRequired;
}
}
| d0c579c31fb34047905e030764c272dc602a1be9 | [
"Java"
] | 1 | Java | gaetanoV94/hibernateMaven | 9fb69b6856e59a05898380257cdaeb2d500007f8 | 47861872c1ad83dd5995887ebd7a9cab8f451b70 | |
refs/heads/master | <file_sep>mocha-inline
============
What is this? This is a really small helper (you could do it in 2 lines, really)
to work with the idea of inlined BDD test blocks. Those are the `describe` and
`it` blocks JavaScript testing frameworks like `mocha` use.
## Rationale and usage
The idea is to write them along your code. When running your code with `mocha`,
`karma` or whatever you want to run them with, they'll be treated as tests. When
running your tests normallly, they'll treated as noops. An example:
```javascript
require('mocha-inline')();
function add(x, y) {
return x + y;
}
describe('add(x, y)', function() {
var assert = require('assert');
it('add(1, 1) is 2', function() {
assert(add(1, 1) === 2);
});
});
```
## TODO Removing inlined tests from built code
**This is not implemented yet**
There's something important this little package should provide: an utility for
removing those test blocks from your code. This is for browser people, who don't
want test blocks to be shipped to clients.
### ... from the command-line
```bash
$ echo "describe('stuff', function() {it('here');});" > example.js
$ mkdir output
$ mocha-inline example.js
Removed 1 `describe` from example.js (example.js -> example-notest.js)
```
## License
This code is licensed under the MIT license. See LICENSE for more information.
<file_sep>require('./')();
function add(x, y) {
return x + y;
}
describe('add(x, y)', function() {
var assert = require('assert');
it('add(1, 1) is 2', function() {
assert(add(1, 1) === 2);
});
});
<file_sep>'use strict';
function ensureGlobal() {
try {
global.stuff = 10;
delete global.stuff;
} catch(err) {
if(err instanceof ReferenceError) {
window.global = window;
}
}
}
function inline() {
ensureGlobal();
if(!global.describe) {
global.describe = function() {};
global.it = function() {};
}
}
exports = module.exports = inline;
| 77d52fccead3204699dee3f04b9507ad7f1c9e14 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | yamadapc/mocha-inline | a4b9c4b39cb93c22f0f2ee70dc466f8c121c43a1 | ebcbb475ebcd58fa8a4e7ffbc243b5fb5c527b6f | |
refs/heads/master | <repo_name>tjorim/addon-sqlite-web<file_sep>/sqlite-web/rootfs/etc/cont-init.d/30-nginx.sh
#!/usr/bin/with-contenv bash
# ==============================================================================
# Community Hass.io Add-ons: SQLite Web
# Configures NGINX for use with SQLite Web
# ==============================================================================
# shellcheck disable=SC1091
source /usr/lib/hassio-addons/base.sh
declare certfile
declare keyfile
# Enable SSL
if hass.config.true 'ssl'; then
rm /etc/nginx/nginx.conf
mv /etc/nginx/nginx-ssl.conf /etc/nginx/nginx.conf
certfile=$(hass.config.get 'certfile')
keyfile=$(hass.config.get 'keyfile')
sed -i "s/%%certfile%%/${certfile}/g" /etc/nginx/nginx.conf
sed -i "s/%%keyfile%%/${keyfile}/g" /etc/nginx/nginx.conf
fi
# Disables IPv6 in case its disabled by the user
if ! hass.config.true 'ipv6'; then
sed -i '/listen \[::\].*/ d' /etc/nginx/nginx.conf
fi
# Handles the HTTP auth part
if ! hass.config.has_value 'username'; then
hass.log.warning "Username/password protection is disabled!"
sed -i '/auth_basic.*/d' /etc/nginx/nginx.conf
else
username=$(hass.config.get 'username')
password=$(hass.config.get 'password')
htpasswd -bc /etc/nginx/.htpasswd "${username}" "${password}"
fi
<file_sep>/sqlite-web/rootfs/etc/cont-init.d/20-patches.sh
#!/usr/bin/with-contenv bash
# ==============================================================================
# Community Hass.io Add-ons: SQLite Web
# This files adds some patches to the add-on
# ==============================================================================
# Adds favicon
mv /www/favicon.png /usr/lib/python3.6/site-packages/sqlite_web/static/img/
patch /usr/lib/python3.6/site-packages/sqlite_web/templates/base.html /patches/favicon
# Adds buymeacoffe link
patch /usr/lib/python3.6/site-packages/sqlite_web/templates/base_tables.html /patches/buymeacoffee
<file_sep>/sqlite-web/Dockerfile
ARG BUILD_FROM=hassioaddons/base:2.3.0
# hadolint ignore=DL3006
FROM ${BUILD_FROM}
# Set shell
SHELL ["/bin/bash", "-o", "pipefail", "-c"]
# Setup base
RUN \
apk add --no-cache --virtual .build-dependencies \
g++=6.4.0-r9 \
gcc=6.4.0-r9 \
make=4.2.1-r2 \
python3-dev=3.6.6-r0 \
&& apk add --no-cache \
apache2-utils=2.4.35-r0 \
nginx=1.14.1-r0 \
python3=3.6.6-r0 \
cython=0.28.2-r0 \
&& pip3 install --no-cache-dir \
flask==1.0.2 \
peewee==3.7.1 \
sqlite-web==0.3.5 \
datasette==0.25.1 \
&& apk del --purge .build-dependencies \
&& find /usr/lib/python3.6/ -type d -name test -depth -exec rm -rf {} \; \
&& find /usr/lib/python3.6/ -type d -name tests -depth -exec rm -rf {} \; \
&& find /usr/lib/python3.6/ -name __pycache__ -depth -exec rm -rf {} \;
# Copy root filesystem
COPY rootfs /
# Build arugments
ARG BUILD_ARCH
ARG BUILD_DATE
ARG BUILD_REF
ARG BUILD_VERSION
# Labels
LABEL \
io.hass.name="Sqlite-web" \
io.hass.description="Explore your SQLite database" \
io.hass.arch="${BUILD_ARCH}" \
io.hass.type="addon" \
io.hass.version=${BUILD_VERSION} \
maintainer="<NAME> @ludeeus <<EMAIL>>" \
org.label-schema.description="Explore your SQLite database" \
org.label-schema.build-date=${BUILD_DATE} \
org.label-schema.name="Sqlite-web" \
org.label-schema.schema-version="1.0" \
org.label-schema.url="https://community.home-assistant.io/t/community-hass-io-add-on-sqlite-web/68912" \
org.label-schema.usage="https://github.com/hassio-addons/addon-sqlite-web/tree/master/README.md" \
org.label-schema.vcs-ref=${BUILD_REF} \
org.label-schema.vcs-url="https://github.com/hassio-addons/addon-sqlite-web" \
org.label-schema.vendor="Community Hass.io Add-ons"
<file_sep>/sqlite-web/rootfs/etc/cont-init.d/10-requirements.sh
#!/usr/bin/with-contenv bash
# ==============================================================================
# Community Hass.io Add-ons: SQLite Web
# This files check if all user configuration requirements are met
# ==============================================================================
# shellcheck disable=SC1091
source /usr/lib/hassio-addons/base.sh
# Require username / password
if ! hass.config.has_value 'username' \
&& ! ( \
hass.config.exists 'leave_front_door_open' \
&& hass.config.true 'leave_front_door_open' \
);
then
hass.die 'You need to set a username!'
fi
if ! hass.config.has_value 'password' \
&& ! ( \
hass.config.exists 'leave_front_door_open' \
&& hass.config.true 'leave_front_door_open' \
);
then
hass.die 'You need to set a password!';
fi
# Require a secure password
if hass.config.has_value 'password' \
&& ! hass.config.is_safe_password '<PASSWORD>'; then
hass.die "Please choose a different password, this one is unsafe!"
fi
# Check SSL requirements, if enabled
if hass.config.true 'ssl'; then
if ! hass.config.has_value 'certfile'; then
hass.die 'SSL is enabled, but no certfile was specified'
fi
if ! hass.config.has_value 'keyfile'; then
hass.die 'SSL is enabled, but no keyfile was specified'
fi
if ! hass.file_exists "/ssl/$(hass.config.get 'certfile')"; then
hass.die 'The configured certfile is not found'
fi
if ! hass.file_exists "/ssl/$(hass.config.get 'keyfile')"; then
hass.die 'The configured keyfile is not found'
fi
fi
# Check if database file exist
if ! hass.file_exists "/config/$(hass.config.get 'database_path')"; then
hass.die 'The configured database file is not found'
fi
| 3797c237da05b55d0996e4ea37bf95108095b7bb | [
"Dockerfile",
"Shell"
] | 4 | Shell | tjorim/addon-sqlite-web | 0b574fab425615410b10960f46af9c08f9d00150 | e07e877cbd8873e20a4fed6022df56db946cd953 | |
refs/heads/master | <repo_name>zstrad44/Kele<file_sep>/lib/kele/roadmap.rb
module Roadmap
def get_roadmap(roadmap_id)
receive = self.class.get(@api_url + '/roadmaps/' + roadmap_id.to_s, headers: { "authorization" => @auth_token })
JSON.parse(receive.body)
end
def get_checkpoint(checkpoint_id)
receive = self.class.get(@api_url + '/checkpoints/' + checkpoint_id.to_s, headers: { "authorization" => @auth_token })
JSON.parse(receive.body)
end
end
<file_sep>/lib/kele.rb
require "httparty"
require "json"
require_relative "kele/roadmap"
class Kele
include HTTParty
include Roadmap
def initialize(email, password)
@api_url = 'https://www.bloc.io/api/v1'
receive = self.class.post(@api_url + '/sessions',
body: {
'email': email,
'password': <PASSWORD>
})
raise ArgumentError, "Email or password is invalid, please try again" unless receive.code == 200
@auth_token = receive["auth_token"]
end
def get_me
receive = self.class.get(@api_url + '/users/me', headers: { "authorization" => @auth_token })
JSON.parse(receive.body)
end
def get_mentor_availability(mentor_id)
receive = self.class.get(@api_url + '/mentors/' + mentor_id.to_s + '/student_availability', headers: { "authorization" => @auth_token })
JSON.parse(receive.body).to_a
end
def get_messages(page)
receive = self.class.get(@api_url + '/message_threads/', headers: { "authorization" => @auth_token }, body: {"page": page })
@messages = JSON.parse(receive.body)
end
def create_message(sender, recipient_id, token, subject, body)
receive = self.class.post(@api_url + '/messages',
headers: { "authorization" => @auth_token },
body: {
"sender": sender,
"recipient_id": recipient_id,
"token": token,
"subject": subject,
"stripped-text": body})
end
def create_submission(assignment_branch, assignment_commit_link, checkpoint_id, comment, enrollment_id)
receive = self.class.post(@api_url + '/checkpoint_submissions',
headers: { "authorization" => @auth_token },
body: {
"assignment_branch": assignment_branch,
"assignment_commit_link": assignment_commit_link,
"checkpoint_id": checkpoint_id,
"comment": comment,
"enrollment_id": enrollment_id })
end
end
<file_sep>/README.md
# Kele
# Kele
| 2404c7c6da1fcf958b5a581eca22fbd4b53ca50f | [
"Markdown",
"Ruby"
] | 3 | Ruby | zstrad44/Kele | 3377fbedb0a917a7f26dfd056c94e6c9bafb9e13 | f60295fab1b24b3fe4b42aaaab807c15f7b596a4 | |
refs/heads/master | <repo_name>rishano/react-youtube-app<file_sep>/build/precache-manifest.04aff5d1f302f2a32bc6029be9b6f477.js
self.__precacheManifest = [
{
"revision": "8fedc4fd322e605902bf",
"url": "/static/css/main.8b61810b.chunk.css"
},
{
"revision": "8fedc4fd322e605902bf",
"url": "/static/js/main.8fedc4fd.chunk.js"
},
{
"revision": "945513008b33705d0de2",
"url": "/static/js/1.94551300.chunk.js"
},
{
"revision": "229c360febb4351a89df",
"url": "/static/js/runtime~main.229c360f.js"
},
{
"revision": "7a49176be039f12e1bd4402f819bb9c1",
"url": "/index.html"
}
]; | f1124ca4514f65278f5a8345206eccf238633c3c | [
"JavaScript"
] | 1 | JavaScript | rishano/react-youtube-app | 2ddfcf2ed0eb819201999dc119503e9ff1b56b26 | 4cebfb6479dae1d4498b4d1a30174505a57437ee | |
refs/heads/master | <file_sep>Rails.application.routes.draw do
get 'product/new'
get 'company/new'
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/companies', to: 'company#index'
get '/create_company', to: 'company#new'
post '/companies', to: 'company#create'
get '/api/companies', to: 'company#indexApi'
get '/products', to: 'product#index'
get '/new_product', to: 'product#new'
post '/products', to: 'product#create'
get '/api/products', to: 'product#showApi'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users
resources :company
resources :product
end
<file_sep>require 'test_helper'
class CompanyRegisterTest < ActionDispatch::IntegrationTest
test "invalid register information" do
get companies_path
#If the POST request is bad, we check that the user hasn't been added (ie we still have the same number of users)
assert_no_difference 'Company.count' do
post companies_path, params: { company: { name: "",
nb_employees: "",
city: "",
turnover: "",
phone: "" } }
end
end
test "valid signup information" do
get companies_path
#If the POST request is ok, we expect a count difference of 1 in the number or users
assert_difference 'Company.count', 1 do
post companies_path, params: { company: { name: "Company",
nb_employees: "10",
city: "London",
turnover: "10000000",
phone: "7817817397" } }
end
end
end
<file_sep>class Company < ApplicationRecord
validates :name, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false }
validates :nb_employees, presence: true
validates :city, presence: true
validates :phone, presence: true
end
<file_sep>class ProductController < ApplicationController
before_action :logged_in_user, only: [:new, :index]
def new
@product= Product.new
@company= Company.find_by(id: current_user.company_id)
end
def show
@product = Product.find(params[:id])
end
def index
@products = Product.paginate(page: params[:page])
end
def create
@product = Product.new(product_params)
if @product.save
flash[:success] = "Successfully created a product"
redirect_to products_path
else
render 'new'
end
end
def showApi
@products = Product.where(company_id: params[:company_id])
render json: @products
end
def destroy
Product.find(params[:id]).destroy
flash[:success] = "Product deleted"
redirect_to products_path
end
private
def product_params
params.require(:product).permit(:name, :description, :price, :company_id)
end
end
<file_sep>require 'test_helper'
class ProductControllerTest < ActionDispatch::IntegrationTest
test "should redirect when not logged in" do
get products_path
assert_redirected_to login_url
end
end
<file_sep>require 'test_helper'
class CompanyControllerTest < ActionDispatch::IntegrationTest
test "should get redirected when not logged in" do
get companies_path
assert_redirected_to login_url
end
end
<file_sep>class CompanyController < ApplicationController
before_action :logged_in_user, only: [:index]
def new
@company= Company.new
end
def show
@company = Company.find(params[:id])
@users = User.where(company_id: params[:id])
end
def index
@companies = Company.paginate(page: params[:page])
end
def indexApi
@companies = Company.paginate(page: params[:page])
render json: @companies
end
def create
@company = Company.new(company_params)
if @company.save
flash[:success] = "Successfully created a company"
redirect_to signup_path
else
render 'new'
end
end
# When destroying a company, all users and products are destroyed
def destroy
User.where(company_id: params[:id]).destroy_all
Product.where(company_id: params[:id]).destroy_all
Company.find(params[:id]).destroy
flash[:success] = "Company deleted"
redirect_to companies_path
end
private
def company_params
params.require(:company).permit(:name,:nb_employees, :city, :turnover,:phone)
end
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
User.create!(name: "Admin",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>",
company_id: 1,
admin: true)
Company.create!(name: "Pro-Duct",
nb_employees:1,
city: "Compiègne",
phone: "0781781739",
turnover: 100000000)
30.times do |n|
name = Faker::Company.name
nb_employees = Faker::Company.duns_number
city = Faker::Address.city
phone = Faker::PhoneNumber.phone_number
turnover = rand(1000...300000000)
Company.create!(name: name,
nb_employees: nb_employees,
city: city,
phone: phone,
turnover: turnover)
end
60.times do |n|
name = Faker::Name.name
email = Faker::Internet.safe_email
password = "<PASSWORD>"
company_id = rand(1...30)
User.create!(name: name,
email: email,
password: <PASSWORD>,
password_confirmation: <PASSWORD>,
company_id: company_id)
end
61.times do |n|
name = Faker::Commerce.product_name
description = Faker::Hacker.say_something_smart
price = Faker::Commerce.price
company_id = rand(1...30)
Product.create!(name: name,
description: description,
price: price,
company_id: company_id)
end<file_sep>require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
test "invalid signup information" do
get signup_path
#If the POST request is bad, we check that the user hasn't been added (ie we still have the same number of users)
assert_no_difference 'User.count' do
post users_path, params: { user: { name: "",
email: "user@invalid",
company_id: 0,
password: "foo",
password_confirmation: "bar" } }
end
assert_template 'users/new'
end
test "valid signup information" do
get signup_path
#If the POST request is ok, we expect a count difference of 1 in the number or users
assert_difference 'User.count', 1 do
post users_path, params: { user: { name: "<NAME>",
email: "<EMAIL>",
company_id: 3,
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>" } }
end
end
end
| 3f620790f24640459b7167a2d0978678e0fd26a5 | [
"Ruby"
] | 9 | Ruby | Rolando-B/rails_first_app | 36807e4446c8e72532d60f393fb1c70d2a2252a8 | 6c8200c0cca1309883f3c8584ad533b9d1b18656 | |
refs/heads/main | <file_sep>import streamlit as st
from predict_page import show_predict_page
show_predict_page()<file_sep>import streamlit as st
import pickle
import numpy as np
def load_model():
with open('saved_steps.pkl', 'rb') as file:
data = pickle.load(file)
return data
data = load_model()
regressor = data["model"]
le_CategoryID = data["le_CategoryID"]
le_bucketovd = data["le_bucketovd"]
le_typeRepoFee = data["le_typeRepoFee"]
le_Kasus = data["le_Kasus"]
le_kondisiAset = data["le_kondisiAset"]
le_kondisi = data["le_kondisi"]
def show_predict_page():
st.title("MTF Collection Fee Estimator")
st.write("""### We need some information to estimate the Collection Fee""")
CategoryID = (
"PASSENGER",
"PICK UP ",
"TRUCK ",
"BULDOZER ",
"MOTOR",
"Excavator ",
"Truck-HE ",
"GENERATOR ",
"TRACTORS ",
"MOTORGRAD ",
"PUMP ",
"LANDFILL ",
)
bucketovd = (
"1. 0-30",
"Writeoff",
"2. 31-60",
"3. 61-90",
"4. 91-120",
"5. 121-150",
"6. 151-180",
"7. >180",
)
typeRepoFee = (
"fee_standar",
"fee_standar_plus_expense",
)
Kasus = (
"unknown",
"Kasus",
"Kasus Berat",
"Administratif",
)
kondisiAset = (
"Asset Atas Nama",
"Asset ada di luar kota",
"Asset ada di dalam kota",
"Biaya sayembara",
)
kondisi = (
"Customer ada, unit tidak ada",
"Customer ada, unit ada",
"Customer tidak ada, unit ada",
"Customer tidak ada, unit tidak ada",
)
selCategoryID = st.selectbox("CategoryID", CategoryID)
selbucketovd = st.selectbox("bucketovd", bucketovd)
seltypeRepoFee = st.selectbox("typeRepoFee", typeRepoFee)
selKasus = st.selectbox("Kasus", Kasus)
selkondisiAset = st.selectbox("kondisiAset", kondisiAset)
selkondisi = st.selectbox("kondisi", kondisi)
ok = st.button("Estimate Collection Fee")
if ok:
X = np.array([[selCategoryID, selbucketovd, seltypeRepoFee, selKasus, selkondisiAset, selkondisi]])
X[:, 0] = le_CategoryID.transform(X[:,0])
X[:, 1] = le_bucketovd.transform(X[:,1])
X[:, 2] = le_typeRepoFee.transform(X[:,2])
X[:, 3] = le_Kasus.transform(X[:,3])
X[:, 4] = le_kondisiAset.transform(X[:,4])
X[:, 5] = le_kondisi.transform(X[:,5])
X = X.astype(float)
collFee = regressor.predict(X)
collFee = int(collFee)
collFeeIntLower = collFee - 2500000
collFeeIntUpper = collFee + 2500000
if (collFee <= 2500000) and (collFee >= 1000000):
collFeeIntLower = 500000
if (collFee < 1000000):
collFeeIntLower = 50000
collFeeIntUpper = 1000000
st.subheader(f"The estimated range of collection fee is IDR {collFeeIntLower} - IDR {collFeeIntUpper}")
<file_sep>numpy==1.17.4
streamlit==0.88.0
scikit-learn==0.22.1
pickleshare==0.7.5 | 62f10a60561da20e1b85bd32046a00b1f379656b | [
"Python",
"Text"
] | 3 | Python | wirahitaputramas/CollFee-Estimator | 4b2cb12fb2254dc19a63157a5577e5b034067b5b | 170aeaa586d38e0aed5379eda8cdebe7eadf0e14 | |
refs/heads/master | <repo_name>megabites2013/threadtest<file_sep>/src/main/java/com/wcc/threadtest/generator/DetailGenerator.java
package com.wcc.threadtest.generator;
import com.wcc.threadtest.model.Detail;
import com.wcc.threadtest.model.Person;
import com.wcc.threadtest.model.Sex;
import com.wcc.threadtest.repository.DetailRepository;
import com.wcc.threadtest.threadtest.service.RandomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import lombok.Data;
@Component
public class DetailGenerator implements Generator {
@Autowired
private DetailRepository detailRepository;
@Autowired
private RandomService r;
@Override
public Person generate(Person person) {
foo();
Detail d = new Detail();
d.setAge(r.getRandomInt());
d.setLength(r.getRandomFloat());
d.setWeight(r.getRandomFloat());
d.setSalary(r.getRandomFloat());
d.setSex(Sex.getRandom());
detailRepository.save(d);
person.setInfo(d);
//System.out.print("D");
return person;
}
}
<file_sep>/src/main/java/com/wcc/threadtest/service/InitService.java
package com.wcc.threadtest.service;
import com.wcc.threadtest.controller.PersonController;
import com.wcc.threadtest.model.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
@Slf4j
@Service
public class InitService {
@Autowired private ExecutorService executorService;
@Autowired private com.wcc.threadtest.threadtest.service.RandomService r;
@Autowired private PersonController controller;
private int howManyGroups = 288;
private Map<Integer, List<Person>> works;
public InitService() {
works = new HashMap();
}
public void populateDB() {
long startTime = System.nanoTime();
long count = 0;
while (howManyGroups > 0) {
getPeoplesParallel(howManyGroups);
howManyGroups--;
}
long endTime = System.nanoTime();
for (List<Person> list : works.values()) {
count += list.size();
}
log.info(
"@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ done = " + count + " in " + (endTime - startTime));
}
private void getPeoplesParallel(int howManyGroups) {
executorService.submit(
() -> {
getPeoples(howManyGroups);
});
}
public void getPeoples(int howManyGroups) {
List<Person> ps = new ArrayList<>();
Long numbers = r.getRandomLong();
if (howManyGroups == 1 || howManyGroups == 200 || howManyGroups == 100) {
numbers = 10000L;
} else {
numbers = 30L;
}
log.info("---------Group No:" + howManyGroups + " --------------> " + numbers + " Persons");
while (numbers > 0) {
ps.add(controller.createPerson("" + howManyGroups + "-" + numbers));
numbers--;
}
log.info("++++++++++++ created " + ps.size() + " for Group No: " + howManyGroups + " +++ ");
works.put(howManyGroups, ps);
}
public void getPeoplesFork(int howManyGroups) {
List<Person> ps = new ArrayList<>();
Long numbers = r.getRandomLong();
if (howManyGroups == 1 || howManyGroups == 200 || howManyGroups == 100) {
numbers = 10000L;
} else {
numbers = 30L;
}
log.info("---------Group No:" + howManyGroups + " --------------> " + numbers + " Persons");
while (numbers > 0) {
ps.add(controller.createPersonFork("" + howManyGroups + "-" + numbers));
numbers--;
}
log.info("++++++++++++ created " + ps.size() + " for Group No: " + howManyGroups + " +++ ");
works.put(howManyGroups, ps);
}
}
<file_sep>/src/main/java/com/wcc/threadtest/generator/DocumentGenerator.java
package com.wcc.threadtest.generator;
import com.wcc.threadtest.model.Document;
import com.wcc.threadtest.model.Person;
import com.wcc.threadtest.repository.DocumentRepository;
import com.wcc.threadtest.threadtest.service.RandomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.Data;
@Component
public class DocumentGenerator implements Generator {
@Autowired
private DocumentRepository documentRepository;
@Autowired
private RandomService r;
@Override
public Person generate(Person person) {
foo();
Document document = new Document();
document.setDocumentStr("setDocumentStr"+r.getRandomInt());
document.setExpireAt(r.getRandomDate());
document.setIssuedAt(r.getRandomDate());
document.setType("DocuTypo"+r.getRandomInt());
documentRepository.save(document);
person.getDocument().add(document);
//System.out.print("T");
return person;
}
}
<file_sep>/src/main/java/com/wcc/threadtest/model/Person.java
package com.wcc.threadtest.model;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Entity
@Data
public class Person {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
String id;
String fName;
String surName;
Date birthDay;
@OneToMany
List<Document> document = new ArrayList<>();
@OneToMany
List<Citizen> citizen = new ArrayList<>();
@OneToOne
Detail info;
}
<file_sep>/src/main/java/com/wcc/threadtest/model/Sex.java
package com.wcc.threadtest.model;
import javax.persistence.Entity;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public enum Sex {
Male,Female,Unkown,Both,WontTell;
private static final List<Sex> VALUES =
Collections.unmodifiableList(Arrays.asList(values()));
private static final int SIZE = VALUES.size();
private static final Random RANDOM = new Random();
public static Sex getRandom() {
return VALUES.get(RANDOM.nextInt(SIZE));
}
}
<file_sep>/src/main/java/com/wcc/threadtest/repository/PersonRepository.java
package com.wcc.threadtest.repository;
import com.wcc.threadtest.model.Person;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface PersonRepository extends JpaRepository<Person, Integer> {}
<file_sep>/src/main/java/com/wcc/threadtest/ThreadtestApplication.java
package com.wcc.threadtest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SpringBootApplication
public class ThreadtestApplication {
public static void main(String[] args) {
SpringApplication.run(ThreadtestApplication.class, args);
}
@Bean
public ExecutorService getExecutorService() {
return Executors.newFixedThreadPool(20);
}
}
<file_sep>/src/main/java/com/wcc/threadtest/controller/PersonController.java
package com.wcc.threadtest.controller;
import com.wcc.threadtest.generator.Generator;
import com.wcc.threadtest.model.Person;
import com.wcc.threadtest.repository.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
@Controller
public class PersonController {
@Autowired
private PersonRepository personRepository;
@Autowired
private List<Generator> generators;
@Autowired
private ExecutorService executorService;
@Autowired
private com.wcc.threadtest.threadtest.service.RandomService r;
public Person createPerson(String s) {
List<Generator> b = new ArrayList<Generator>(generators);
Person p = new Person();
p.setFName(s);
p.setSurName(s);
p.setBirthDay(r.getRandomDate());
for (Generator generator : b) {
p=generator.generate(p);
}
personRepository.save(p);
return p;
}
public Person createPersonFork(String s) {
List<Generator> b = new ArrayList<Generator>(generators);
Person p = new Person();
p.setFName(s);
p.setSurName(s);
p.setBirthDay(r.getRandomDate());
b.parallelStream().forEach(g -> g.generate(p));
personRepository.save(p);
return p;
}
}
| 03857a47f9928a795562f2d913030ec488a0b8f1 | [
"Java"
] | 8 | Java | megabites2013/threadtest | 4d52cd2f45bf5eecaca10a76da6a791363d2db01 | aa7809371e54171b3d7f03417dbcf2d7f9bd20e6 | |
refs/heads/master | <repo_name>Oscar16A/STC3<file_sep>/Assets/Scripts/Christian/Obstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Obstacle : MonoBehaviour
{
// Obstacle movement
public float xScroll;
public bool dependent = true; // false = movement independent of xScroll
// Obstacle health/damage
public int health = -1, damage = 1;
// Technical stuffs
private Vector2 screenBounds;
private float xSize; // Half the size of the obstacle for offscreen object destruction purposes
// Initializes the obstacle's fields
protected abstract void StartObstacle();
// Updates the obstacle's movement
protected abstract void MoveObstacle(bool dependent);
void Start()
{
// Set obstacle fields
StartObstacle();
// Get boundaries for off camera game object despawning
screenBounds = new Vector2(-Camera.main.aspect * Camera.main.orthographicSize, Camera.main.orthographicSize);
// Edge offset of object
xSize = GetComponent<SpriteRenderer>().bounds.size.x / 2;
}
void FixedUpdate()
{
// Update obstacles movement (velocity/acceleration)
MoveObstacle(dependent);
// Object gets uninstantiated once off the camera (dependent of x axis position)
if (xScroll > 0 && transform.position.x > -screenBounds.x + xSize)
{
Destroy(this.gameObject);
}
if (xScroll < 0 && transform.position.x < screenBounds.x - xSize)
{
Destroy(this.gameObject);
}
}
}
<file_sep>/Assets/Scripts/Jason/SceneManager.cs
using UnityEngine;
public class SceneManager : MonoBehaviour
{
void Start()
{
}
private void ShowScene (string sceneName)
{
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
}
public void ShowMainMenuScene()
{
// ShowScene("MainMenu");
}
public void ShowGameScene()
{
// ShowScene("MainMenu");
}
public void ShowCreditsScene()
{
// ShowScene("MainMenu");
}
public void ShowOptionsScene()
{
// ShowScene("MainMenu");
}
}
<file_sep>/Assets/Scripts/Christian/PauseAccelObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PauseAccelObstacle : PauseObstacle
{
// Default inital and final accelerations
public float xAccelInit = 0f, yAccelInit = 0f;
public float xAccelFinal = 0f, yAccelFinal = 0f;
// Private modifiable velocities
protected float xAccel, yAccel;
// State tracking variable
private bool completed = false;
protected override void StartObstacle()
{
base.StartObstacle();
// Adjust accelerations in direction of xScroll
xAccelInit *= direction;
xAccelFinal *= direction;
// Set accelerations
xAccel = xAccelInit;
yAccel = yAccelInit;
}
protected override void MoveObstacle(bool dependent)
{
AdjustAccelerations();
xVel += xAccel;
yVel += yAccel;
base.MoveObstacle(dependent);
}
// Adjusts the accelerations according to the time stamps
protected void AdjustAccelerations()
{
if (!completed && timeElapsed < unpause && timeElapsed >= waitSeconds)
{
xAccel = 0;
yAccel = 0;
}
else if (!completed && timeElapsed >= unpause)
{
xAccel = xAccelFinal;
yAccel = yAccelFinal;
completed = true;
}
}
}
<file_sep>/Assets/Scripts/Christian/StaticObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StaticObstacle : Obstacle
{
// Default velocities
private readonly float xVel = 0f, yVel = 0f;
// Velocity vectors
private Vector2 velocityRelative; // Does not include the xScroll
private Vector2 velocityTrue; // Includes the xScroll
protected override void StartObstacle()
{
velocityRelative = new Vector2(xVel, yVel);
velocityTrue = new Vector2(xScroll + xVel, yVel);
}
protected override void MoveObstacle(bool dependent)
{
transform.Translate((dependent) ? velocityTrue : velocityRelative);
}
}
<file_sep>/README.md
# STC3
VGDC Quarter Project Fall 2019
<file_sep>/Assets/Scripts/Christian/SegmentSpawner.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
public class SegmentSpawner : MonoBehaviour
{
public float xScroll;
// Variables regarding to the segment prefabs
public Segment[] segments;
private Vector2 screenBounds;
private Segment currentSegment, nextSegment;
private float prevSpawnPos;
private int prevIndex1, prevIndex2;
void Start()
{
screenBounds = new Vector2(-Camera.main.aspect * Camera.main.orthographicSize, Camera.main.orthographicSize);
//Debug.Log("+x bound: " + screenBounds.x + " -x bound: " + -screenBounds.x);
segments = LoadSegments();
int index = Random.Range(0, segments.Length);
prevIndex2 = prevIndex1;
prevIndex1 = index;
currentSegment = InstantiateSegment(segments[index]);
if (xScroll < 0)
{
prevSpawnPos = currentSegment.GetXMin();
}
else if (xScroll > 0)
{
prevSpawnPos = currentSegment.GetXMax();
}
}
void FixedUpdate()
{
if (xScroll < 0 && currentSegment.GetXMax() < prevSpawnPos)
{
int index = UniqueIndex(segments.Length, new int[] {prevIndex1, prevIndex2});
currentSegment = InstantiateSegment(segments[index]);
prevSpawnPos = currentSegment.GetXMin();
Debug.Log(index + " " + prevIndex1 + " " + prevIndex2);
prevIndex2 = prevIndex1;
prevIndex1 = index;
}
else if (xScroll > 0 && currentSegment.GetXMin() > prevSpawnPos)
{
int index = UniqueIndex(segments.Length, new int[] { prevIndex1, prevIndex2 });
currentSegment = InstantiateSegment(segments[index]);
prevSpawnPos = currentSegment.GetXMax();
prevIndex2 = prevIndex1;
prevIndex1 = index;
}
}
// Changes the scroll speed of all instantiated segments
public void UpdateScroll(float x)
{
xScroll = x;
foreach (Segment segment in segments)
{
segment.xScroll = xScroll;
}
}
// Initializes segment values and instantiates it into the scene
private Segment InstantiateSegment(Segment segment)
{
segment.xScroll = xScroll;
float x = segment.transform.position.x;
// If xScroll is negative, load segment prefab on left side of screen
if (xScroll < 0)
{
x = -screenBounds.x + (segment.transform.position.x - segment.GetXMin());
}
// If xScroll is positive, load segment prefab on right side of screen
if (xScroll > 0)
{
x = screenBounds.x - (segment.GetXMax() - segment.transform.position.x);
}
segment.transform.position = new Vector3(x, 0, segment.transform.position.z);
// Instantiates the segment prefab into the scene
return Instantiate(segment).GetComponent<Segment>();
}
// Generates a random index that is not in the excluded indices
private int UniqueIndex(int range, int[] exclude)
{
int index = -1;
bool contains = false;
do
{
index = Random.Range(0, range);
// Check if the new index is inside the exluded indices
contains = false;
foreach (int num in exclude)
{
if (index == num)
{
contains = true;
break;
}
}
} while (contains);
return index;
}
// Takes in a the directory path for the prefabs and returns an array of only segment game objects
private Segment[] LoadSegments()
{
// Get all prefab file paths from the directory
// string directoryPath = Application.dataPath + "/" + directory;
// string[] filePaths = Directory.GetFileSystemEntries(directoryPath, "*.prefab");
// Load all segments from the Resources folder
GameObject[] prefabs = Resources.LoadAll<GameObject>("");
List<Segment> segments = new List<Segment>();
foreach (GameObject prefab in prefabs)
{
if (prefab.GetComponent<Segment>())
{
segments.Add(prefab.GetComponent<Segment>());
}
}
// Return array version of the list
return segments.ToArray();
}
}
<file_sep>/Assets/Scripts/Lillian/testParallax.cs
using System.Collections;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
public class testParallax : MonoBehaviour
{
// scrolling speed
public Vector2 speed = new Vector2(2, 2);
// direction
public Vector2 direction = new Vector2(-1, 0);
public bool isLinkedToCamera = false;
// check if bg is infinite
public bool bgLoop = false;
//public bool mgLoop = false;
private List<SpriteRenderer> backgroundPart;
// Start is called before the first frame update
void Start()
{
if (bgLoop)
{
backgroundPart = new List<SpriteRenderer>();
for ( int i = 0; i < transform.childCount;i++)
{
Transform child = transform.GetChild(i);
SpriteRenderer r = child.GetComponent<SpriteRenderer>();
if ( r != null )
{
backgroundPart.Add(r);
}
}
// Sort
backgroundPart = backgroundPart.OrderBy(t => t.transform.position.x).ToList();
}
}
// Update is called once per frame
void Update()
{
// start moving the bg
Vector3 movement = new Vector3( speed.x * direction.x, speed.y * direction.y, 0);
movement *= Time.deltaTime;
transform.Translate(movement);
// now move cam
if ( isLinkedToCamera)
{
Camera.main.transform.Translate(movement);
}
if ( bgLoop)
{
SpriteRenderer firstChild = backgroundPart.FirstOrDefault();
if (firstChild != null )
{
if ( firstChild.transform.position.x < Camera.main.transform.position.x)
{
if (firstChild.IsVisibleFrom(Camera.main) == false)
{
SpriteRenderer lastChild = backgroundPart.LastOrDefault();
Vector3 lastPos = lastChild.transform.position;
Vector3 lastSize = (lastChild.bounds.max - lastChild.bounds.min);
firstChild.transform.position = new Vector3( lastPos.x + lastSize.x,
firstChild.transform.position.y, firstChild.transform.position.z);
backgroundPart.Remove(firstChild);
backgroundPart.Add(firstChild);
}
}
}
}
}
}<file_sep>/Assets/Scripts/Christian/Segment.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Segment : MonoBehaviour
{
public int difficulty = 1; // Segment difficulty tag: 1 = easiest ... infinite = hardest
public float xScroll;
void Start()
{
foreach(Obstacle obstacle in GetComponentsInChildren<Obstacle>())
{
obstacle.xScroll = xScroll;
}
}
void FixedUpdate()
{
// If the segment has no more children components, destory the segment
if (GetComponentsInChildren<Obstacle>().Length == 0)
{
Destroy(this.gameObject);
}
}
// Returns the x position of the leftmost edge relative to the x position of the segment
public float GetXMin()
{
Obstacle[] obstacles = GetComponentsInChildren<Obstacle>();
// Return a zero early if there is less than one obstacles in the segment
if (obstacles.Length < 1)
{
return 0;
}
float minXPos = obstacles[0].transform.position.x;
float minXScale = obstacles[0].GetComponent<SpriteRenderer>().bounds.size.x / 2;
// Compare each child obstacle of the segment game object to determine min and max
for (int i = 0; i < obstacles.Length; i++)
{
float currentXPos = obstacles[i].transform.position.x;
float currentXScale = obstacles[i].GetComponent<SpriteRenderer>().bounds.size.x / 2;
// Compare for minimum x position
if (currentXPos - currentXScale < minXPos - minXScale)
{
minXPos = currentXPos;
minXScale = currentXScale;
}
}
return minXPos - minXScale;
}
// Returns the x position of the rightmost edge relative to the x position of the segment
public float GetXMax()
{
Obstacle[] obstacles = GetComponentsInChildren<Obstacle>();
// Return a zero early if there is less than one obstacles in the segment
if (obstacles.Length < 1)
{
return 0;
}
float maxXPos = obstacles[0].transform.position.x;
float maxXScale = obstacles[0].GetComponent<SpriteRenderer>().bounds.size.x / 2;
// Compare each child obstacle of the segment game object to determine min and max
for (int i = 1; i < obstacles.Length; i++)
{
float currentXPos = obstacles[i].transform.position.x;
float currentXScale = obstacles[i].GetComponent<SpriteRenderer>().bounds.size.x / 2;
// Compare for maximum x position
if (currentXPos + currentXScale > maxXPos + maxXScale)
{
maxXPos = currentXPos;
maxXScale = currentXScale;
}
}
return maxXPos + maxXScale;
}
// Returns the width of the segment from the lowest x-axis edge to the highest x-axis edge
public float GetXSize()
{
return GetXMax() - GetXMin();
}
}
<file_sep>/Assets/Scripts/Oscar/testmenu.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class testmenu : MonoBehaviour
{
public void loadGame()
{
UnityEngine.SceneManagement.SceneManager.LoadScene("Test Gameplay");
}
public void quit()
{
Debug.Log("Quit Game");
Application.Quit();
}
}
<file_sep>/Assets/Scripts/Oscar/backtomenu.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class backtomenu : MonoBehaviour
{
void Update()
{
if(Input.GetButtonDown("Cancel"))
{
UnityEngine.SceneManagement.SceneManager.LoadScene("Test Main Menu");
}
}
}<file_sep>/Assets/Scripts/Christian/DynamicObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DynamicObstacle : Obstacle
{
// Default velocities and accelerations
public float xVel = 0f, yVel = 0f;
public float xAccel = 0f, yAccel = 0f;
// xScroll direction adjustment variable
private int direction;
// Velocity vectors
private Vector2 velocityRelative; // Does not include the xScroll
private Vector2 velocityTrue; // Includes the xScroll
protected override void StartObstacle()
{
direction = (xScroll < 0) ? -1 : 1;
// Adjust velocity and acceleration into the direction of xScroll
xVel *= direction;
xAccel *= direction;
}
protected override void MoveObstacle(bool dependent)
{
xVel += xAccel;
yVel += yAccel;
if (dependent)
{
transform.Translate(xVel + xScroll, yVel, 0);
}
else
{
transform.Translate(xVel, yVel, 0);
}
}
}
<file_sep>/Assets/Scripts/Christian/PauseObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PauseObstacle : Obstacle
{
// Default inital and final velocities
public float xVelInit = 0f, yVelInit = 0f;
public float xVelFinal = 0f, yVelFinal = 0f;
// Wait and pause times in seconds
public float waitSeconds; // The time before it pauses
public float pauseSeconds; // The time duration of the pause
// Time stamp to unpause
protected float unpause;
// Private modifiable velocities
protected float xVel, yVel;
// xScroll direction adjustment variable
protected int direction;
// Local elapsed time tracking variable
protected float timeElapsed = 0f;
private bool completed = false;
protected override void StartObstacle()
{
direction = (xScroll < 0) ? -1 : 1;
// Adjust velocities into the direction of xScroll
xVelInit *= direction;
xVelFinal *= direction;
// Unpause time stamp
unpause = waitSeconds + pauseSeconds;
// Set velocities
xVel = xVelInit;
yVel = yVelInit;
}
protected override void MoveObstacle(bool dependent)
{
// Set relative velocities according to the time stamps
AdjustVelocities();
// Move the obstacle according to its xScroll dependency
if (dependent)
{
transform.Translate(xVel + xScroll, yVel, transform.position.z);
}
else
{
transform.Translate(xVel, yVel, transform.position.z);
}
timeElapsed += Time.deltaTime;
}
// Adjusts the velocities according to the time stamps
protected void AdjustVelocities()
{
if (!completed && timeElapsed < unpause && timeElapsed >= waitSeconds)
{
xVel = 0;
yVel = 0;
}
else if (!completed && timeElapsed >= unpause)
{
xVel = xVelFinal;
yVel = yVelFinal;
completed = true;
}
}
}
<file_sep>/Assets/Scripts/Christian/SineWaveObstacle.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SineWaveObstacle : Obstacle
{
// Sine wave arguments (in Unity units)
public float amplitude = 1;
public float period = 4;
public float offset = 0;
// xScroll direction adjustment variable
protected int direction;
// Movement/location related variables
private float conversionRatio;
private float xInitPos, yInitPos;
private float xPos, yPos;
// Velocity vectors
private Vector2 velocityRelative; // Does not include the xScroll
private Vector2 velocityTrue; // Includes the xScroll
protected override void StartObstacle()
{
direction = (xScroll < 0) ? -1 : 1;
amplitude *= direction;
offset *= direction;
xInitPos = transform.position.x;
yInitPos = transform.position.y;
xPos = xInitPos;
yPos = yInitPos;
conversionRatio = (2 * Mathf.PI) / period;
offset *= conversionRatio;
}
protected override void MoveObstacle(bool dependent)
{
xPos += xScroll;
yPos = amplitude * Mathf.Sin(xPos * conversionRatio + offset) + yInitPos;
transform.position = new Vector3(xPos, yPos, transform.position.z);
}
}
<file_sep>/Assets/Scripts/Lillian/HighscoreScript.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighscoreScript : MonoBehaviour
{
// Start is called before the first frame update
public Text score;
public void testingFunct()
{
int number = Random.Range(1, 7);
score.text = number.ToString();
//Debug.Log(score);
}
}
| 628122140d5fe5eef8f9f51b0efa9d39e41fdedf | [
"Markdown",
"C#"
] | 14 | C# | Oscar16A/STC3 | 199d00e1842c86a68d4a6080163829cef5b4a47a | fc7d8674c526a88183040ac9e6d414064b104ff3 | |
refs/heads/master | <repo_name>eb01/jeanlorem.io<file_sep>/README.md
# jeanlorem.io
## Présentation
<NAME> est un générateur de texte aléatoire ... sauf qu'en lieu et place du classique lorem ipsum, il utilise les blagues et citations de Jean, le doyen de ma promotion à la 3WA qui nous a toujours épaté par ses envolées lyriques (bon certes, ce n'est pas toujours très fin et ce ne sera pas au goût de tous mais bon !).
L'utilisateur peut générer du texte rapidement en fonction de ses propres choix (nombre de paragraphes, type de titres (h1, h2 ...), balises **p**, contenu tous publics ou adulte).
L'administrateur (Jean, moi-même ou un tiers) peut accéder aux fonctionnalités de visualisation, d'ajout, d'édition et de suppression de blagues/citations.
## Technique
* Côté générateur :
Je voulais que l'utilisateur puisse cliquer autant de fois qu'il le souhaite sur le bouton "Générer" sans que cela génère un rechargement de page.
J'ai donc décidé de récupérer les blagues et citations contenues dans la DB dans un fichier JSON via la fonction native PHP *json_encode()*.
J'ai ensuite travaillé en JS (avec de l'AJAX) pour récupérer les blagues/citations dans le fichier *jokes.json* en fonction des choix utilisateur.
La construction du textarea dynamique se fait avec la fonction *buildRandomJeanLorem()*.
* Côté panel admin :
Je me suis entraîné à travailler avec la variable globale *$_SESSION*.
J'ai fait un maximum de traitement PHP afin de vérifier les entrées utilisateur.
* Librairies :
J'ai choisi de m'entraîner avec jQuery sur ce projet afin de mesurer les différence avec du JS vanilla et j'ai fait des essais avec des plugins notamment pour la validation des formulaires en temps réel afin d'améliorer l'expérience utilisateur (avant les "purs" traitements PHP s'exécutant en validant les formulaires).
J'ai utilisé Bootstrap 3 pour avoir un site responsive de manière efficace et rapide ainsi que pour la mise en forme du menu, des formulaires et du tableau admin.
## Dump DB MySQL
Le fichier .sql contenant les données publiques de la DB est disponible à l'emplacement *resources/dump_db_sql*.
## Site web online
https://jeanlorem.io/<file_sep>/index.php
<?php
session_start();
// DB Connect
require_once __DIR__.'/application/bdd_connection.php';
// Query returning jokes
$query = $pdo->prepare
(
'SELECT
joke_content,
joke_audience,
joke_tagType
FROM
jokes
'
);
$query->execute();
$jokes = $query->fetchAll(PDO::FETCH_ASSOC);
// Encode all jokes in json for manage them with JS
$jokesJson = fopen('jokes.json', 'w');
fwrite($jokesJson, json_encode($jokes));
fclose($jokesJson);
// Page details (for the head)
$title = "Générateur de Lorem Ipsum (ou faux-texte) | <NAME>";
$description = "Un générateur de Lorem Ipsum (ou faux-texte) pas comme les autres. <NAME> met à disposition du lorem au langage fleuri. Du faux-texte humoristique en langue française pour changer du texte latin.";
// Routing
$template = "index";
include 'layout.php';<file_sep>/login.php
<?php
session_start();
// If user is already logged, redirect to admin panel
if(isset($_SESSION['user_ID']) && isset($_SESSION['username'])) {
header('Location: admin');
exit;
};
// If the form is filled
if(!empty($_POST)) {
// DB Connect
require_once __DIR__.'/application/bdd_connection.php';
// Query used for check the identification (username and password)
$query = $pdo->prepare('SELECT * FROM users WHERE user_username = ?');
// Give the username entered by user
$query->execute(array($_POST['username']));
// This returns false if username doesn't exist in DB
$user = $query->fetch(PDO::FETCH_ASSOC);
/* Compare the password entered by user and the password stocked in DB
* Use of password_verify PHP function (encrypted with password_hash)
*/
$checkedPassword = password_verify($_POST['password'], $user['user_password']);
// If user doesn't exist or password doesn't match, display error message
if (!$user || !$checkedPassword) {
$errorLoginMessage = 'Mauvais identifiant ou mot de passe !';
}
// Else, start a user session, prepare flashbag msg
else {
session_start();
$_SESSION['user_ID'] = $user['user_ID'];
$_SESSION['username'] = $user['user_username'];
$_SESSION['successLoginMessage'] = ", tu t'es bien connecté !";
// Query for update the user last login datetime in DB
$query = $pdo->prepare('UPDATE users SET user_dateLastLogin = NOW() WHERE user_ID = ?');
// Give the user_ID
$query->execute(array($_SESSION['user_ID']));
// Redirect to admin panel
header('Location: admin');
exit;
};
};
// Page details (for the head)
$title = "Se connecter | <NAME>";
$description = "Formulaire de connexion au panneau d'administration de Jean Lorem";
// Routing
$template = "login";
include 'layout.php';<file_sep>/delete-joke.php
<?php
session_start();
if(isset($_SESSION['user_ID']) && isset($_SESSION['username'])) {
// DB Connect
require_once __DIR__.'/application/bdd_connection.php';
// If $_GET has a value, , we retrieve all the jokes IDs for check if $_GET value exists in DB
if(!empty($_GET["joke_ID"])) {
// Query for retrieve all the jokes IDs
$query = $pdo->prepare
(
'SELECT
joke_ID
FROM jokes'
);
$query->execute();
$jokes = $query->fetchAll(PDO::FETCH_COLUMN, 0);
// We check if the joke exists in DB before query process
if(in_array($_GET["joke_ID"], $jokes)) {
// Query for delete THE joke
$query = $pdo->prepare
(
'DELETE FROM jokes
WHERE joke_ID = ?'
);
$query->execute(array($_GET["joke_ID"]));
// Prepare flashbag success message and redirect to admin panel
$_SESSION['successDeleteJokeMessage'] = "Blague/citation correctement supprimée";
header("Location: admin");
exit;
};
}
//Else redirect to admin panel
else {
header("Location: admin");
exit;
};
// Else, redirect to homepage
} else {
header('Location: /');
exit;
};
// No routing because this is a "trigger page"
?><file_sep>/edit-joke.php
<?php
session_start();
// If user is logged
if(isset($_SESSION['user_ID']) && isset($_SESSION['username'])) {
// DB Connect
require_once __DIR__.'/application/bdd_connection.php';
// ***CASE 1*** : If the form is empty, first we retrieve all the jokes IDs for check if $_GET value exists in DB
if(empty($_POST)) {
// Query for retrieve all the jokes IDs
$query = $pdo->prepare
(
'SELECT
joke_ID
FROM jokes'
);
$query->execute();
$jokes = $query->fetchAll(PDO::FETCH_COLUMN, 0);
// We check if the joke exists in DB before query process. In the view, we will pre-filled the inputs with these datas.
if(in_array($_GET["joke_ID"], $jokes)) {
// Query for retrieve THE joke
$query = $pdo->prepare
(
'SELECT
joke_content,
joke_audience,
joke_tagType
FROM jokes
WHERE joke_ID = ?'
);
$query->execute(array($_GET["joke_ID"]));
// This returns false if joke doesn't exist in DB
$joke = $query->fetch(PDO::FETCH_ASSOC);
// Else, redirect to admin panel
} else {
header('Location: admin');
exit;
};
}
// ***CASE 2*** : Else, this is the case where the form is filled so we update the DB (after form data treatments)
else {
// For more lisibility
$jokeTagType = $_POST["joke-tagtype"];
$jokeAudience = $_POST["joke-audience"];
$jokeContent = $_POST["joke-content"];
// Prepare form data treatment on characters length range
switch ($jokeTagType) {
case 'paragraph':
$charMinLength = 101;
$charMaxLength = 700;
break;
case 'header':
$charMinLength = 8;
$charMaxLength = 100;
break;
};
// First query : we retrieve all the jokes IDs for check if $_POST value exists in DB
// Query for retrieve all the jokes IDs
$query = $pdo->prepare
(
'SELECT
joke_ID
FROM jokes'
);
$query->execute();
$jokes = $query->fetchAll(PDO::FETCH_COLUMN, 0);
// We check if the joke exists in DB + Form data treatments on selected options and characters length range
// *Info* : here $_POST["joke-id"] returns the value of an input hidden which returns the $_GET["joke_ID"] value
if(in_array($_POST["joke-ID"], $jokes) &&
($jokeTagType === "paragraph" || $jokeTagType === "header") &&
($jokeAudience === "all" || $jokeAudience === "adult") &&
strlen($jokeContent) >= $charMinLength && strlen($jokeContent) <= $charMaxLength) {
// Query for update THE joke in DB
$query = $pdo->prepare
(
'UPDATE
jokes
SET joke_content = ?,
joke_audience = ?,
joke_tagType = ?,
joke_dateLastEdit = NOW()
WHERE joke_ID = ?
'
);
$query->execute(array($jokeContent, $jokeAudience, $jokeTagType, $_POST["joke-ID"]));
// Prepare flashbag success message and redirect to admin panel
$_SESSION["successEditJokeMessage"] = "Blague/Citation éditée avec succès";
header("Location: admin");
exit;
}
// Else, user data is incorrect, so display error message
else {
$errorAddEditJokeMessage = "Merci de renseigner correctement le formulaire";
};
};
// Else, redirect to homepage
} else {
header('Location: /');
exit;
};
// Page details (for the head)
$title = "Éditer une blague/citation | <NAME>";
$description = "Formulaire d'édition d'une blague ou d'une citation";
// Routing
$template = 'edit-joke';
include 'layout.php';<file_sep>/admin.php
<?php
session_start();
// If user is logged
if(isset($_SESSION['user_ID']) && isset($_SESSION['username'])) {
// DB Connect
require_once __DIR__.'/application/bdd_connection.php';
// Query used for retrieve all the jokes and their respectives usernames
$query = $pdo->prepare
(
'SELECT
joke_ID,
joke_content,
joke_audience,
joke_tagType,
joke_dateCreation,
joke_dateLastEdit,
user_username
FROM
jokes
INNER JOIN users
ON jokes.user_ID = users.user_ID
ORDER BY joke_ID
'
);
$query->execute();
$jokes = $query->fetchAll(PDO::FETCH_ASSOC);
// Page details (for the head)
$title = "Admin | <NAME>";
$description = "Panneau d'administration de <NAME>";
// Routing
$template = "admin";
include 'layout.php';
// Else, redirect to homepage
} else {
header('Location: /');
exit;
};<file_sep>/application/bdd_connection.php
<?php
// DB config
$dsn = "mysql:host=localhost;dbname=";
$user = "";
$password = "";
// DB safe connection
try {
$pdo = new PDO($dsn, $user, $password);
// Characters type
$pdo->exec("SET NAMES UTF8");
}
catch (PDOException $e) {
echo $e->getMessage();
}<file_sep>/layout.php
<?php $currentPage = $_SERVER['REQUEST_URI']; ?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title><?= $title ?></title>
<meta name="description" content=<?= '"' . $description . '"' ?> />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="<NAME>" />
<?php if($currentPage != "/" && $currentPage != "/story") : ?>
<meta name="robots" content="noindex, nofollow" />
<?php endif; ?>
<?php if($currentPage == "/" || $currentPage == "/story") : ?>
<meta property="og:site_name" content="<NAME>">
<meta property="og:title" content=<?= '"' . $title . '"' ?> />
<meta property="og:type" content="website" />
<meta property="og:url" content="https://jeanlorem.io/" />
<meta property="og:image" content="https://jeanlorem.io/img/jeanlorem-logo.png" />
<meta property="twitter:card" content="summary" />
<meta property="twitter:site" content="@jeanlorem" />
<meta property="twitter:title" content=<?= '"' . $title . '"' ?> />
<meta property="twitter:description" content=<?= '"' . $description . '"' ?> />
<meta property="twitter:image" content="https://jeanlorem.io/img/jeanlorem-logo.png" />
<meta property="twitter:url" content="https://jeanlorem.io/" />
<?php endif; ?>
<link rel="icon" type="image/png" href="img/jeanlorem-favicon.png" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link href="https://fonts.googleapis.com/css?family=Anonymous+Pro:400,700" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Josefin+Slab:700" rel="stylesheet" />
<link rel="stylesheet" href="css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/jssocials.css" />
<link rel="stylesheet" type="text/css" href="css/jssocials-theme-flat.css" />
<link rel="stylesheet" href="css/style.css" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header>
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Afficher le menu</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/"><NAME></a>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/">Générateur</a></li>
<li><a href="story">The story</a></li>
<?php if(isset($_SESSION['user_ID']) && isset($_SESSION['username'])) : ?>
<li class="dropdown">
<a href="admin" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Admin <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="admin">Gestion des blagues</a></li>
<li><a href="add-joke">Ajouter une blague</a></li>
<li role="separator" class="divider"></li>
<li><a href="disconnect">Déconnexion <?= "(" . $_SESSION['username'] .")" ?></a></li>
</ul>
</li>
<?php endif; ?>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<div class="brand"><a href="/"><NAME></a></div>
<p><strong>Le générateur de langage fleuri</strong></p>
</header>
<main>
<div class="container">
<?php include $template.'.phtml' ?>
</div>
</main>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p>Copyright © <NAME> <?= date("Y"); ?></p>
</div>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="js/jssocials.min.js"></script>
<script src="js/jquery-charactercounter.js"></script>
<script src="js/bootstrap-confirmation.min.js"></script>
<script src="js/main.js"></script>
</body>
</html><file_sep>/add-joke.php
<?php
session_start();
// If user is logged
if(isset($_SESSION['user_ID']) && isset($_SESSION['username'])) {
// If the form is filled
if(!empty($_POST)) {
// For more lisibility
$jokeTagType = $_POST["joke-tagtype"];
$jokeAudience = $_POST["joke-audience"];
$jokeContent = $_POST["joke-content"];
// Prepare form data treatment on characters length range
switch ($jokeTagType) {
case 'paragraph':
$charMinLength = 101;
$charMaxLength = 700;
break;
case 'header':
$charMinLength = 8;
$charMaxLength = 100;
break;
};
// Form data treatments on selected options and characters length range
if( ($jokeTagType === "paragraph" || $jokeTagType === "header") &&
($jokeAudience === "all" || $jokeAudience === "adult") &&
strlen($jokeContent) >= $charMinLength && strlen($jokeContent) <= $charMaxLength) {
// DB Connect
require_once __DIR__.'/application/bdd_connection.php';
// Query for insert a new joke in DB
$query = $pdo->prepare
(
'INSERT INTO
jokes(
joke_content,
joke_audience,
joke_tagType,
joke_dateCreation,
user_ID
)
VALUES(
?,
?,
?,
NOW(),
?
)
'
);
$query->execute(array($jokeContent, $jokeAudience, $jokeTagType, $_SESSION["user_ID"]));
// Prepare flashbag success message and redirect to admin panel
$_SESSION["successAddJokeMessage"] = "Blague/Citation ajoutée avec succès";
header('Location: admin');
exit;
}
// Else, user data is incorrect, so display error message
else {
$errorAddEditJokeMessage = "Merci de renseigner correctement le formulaire";
};
};
// Else, redirect to homepage
} else {
header('Location: /');
exit;
};
// Page details (for the head)
$title = "Ajouter une blague/citation | <NAME>";
$description = "Formulaire d'ajout d'une blague ou d'une citation";
// Routing
$template = "add-joke";
include 'layout.php';<file_sep>/story.php
<?php
session_start();
// Page details (for the head)
$title = "The Story | <NAME>";
$description = "L'histoire de <NAME>. <NAME>, c'est quoi ? Pour qui ? Pourquoi ? Les réponses sont sur cette page !";
// Routing
$template = "story";
include 'layout.php';<file_sep>/resources/dump_db_sql/admin_jeanlorem.sql
-- phpMyAdmin SQL Dump
-- version 4.2.12deb2+deb8u2
-- http://www.phpmyadmin.net
--
-- Client : localhost
-- Généré le : Jeu 26 Octobre 2017 à 17:02
-- Version du serveur : 5.5.57-0+deb8u1
-- Version de PHP : 5.6.30-0+deb8u1
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Base de données : `Private content`
--
-- --------------------------------------------------------
--
-- Structure de la table `jokes`
--
CREATE TABLE IF NOT EXISTS `jokes` (
`joke_ID` int(11) NOT NULL,
`joke_content` text NOT NULL,
`joke_audience` varchar(200) NOT NULL,
`joke_tagType` varchar(200) NOT NULL,
`joke_dateCreation` datetime NOT NULL,
`joke_dateLastEdit` datetime DEFAULT NULL,
`user_ID` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
--
-- Contenu de la table `jokes`
--
INSERT INTO `jokes` (`joke_ID`, `joke_content`, `joke_audience`, `joke_tagType`, `joke_dateCreation`, `joke_dateLastEdit`, `user_ID`) VALUES
(1, 'Pour que ça marche en PHP, il faut avoir des echo logiques hein !', 'all', 'header', '2017-08-25 17:22:27', NULL, 1),
(2, 'Les requêtes SQL, on appelle ça un cercle vicelard', 'all', 'header', '2017-08-25 17:23:00', NULL, 1),
(3, 'Bonjour Macha, mon mari encule mon chat ... est-ce que mon chat est normal ?', 'adult', 'header', '2017-08-25 17:23:47', NULL, 1),
(4, 'Un concentré n''est pas forcément un imbécile qui se trouve au milieu d''un cercle', 'all', 'header', '2017-08-25 17:24:05', NULL, 1),
(5, 'Aujourd''hui qui c''est qui nous apprend Silex ??? ... Bah c''est Pierre !', 'all', 'header', '2017-08-25 17:25:43', NULL, 1),
(6, 'Là on se fait Angular, jeudi on se fera encular', 'adult', 'header', '2017-08-25 17:26:22', NULL, 1),
(7, 'J''avais une faille, je me suis mal préparé, il me l''a mis dans le SQL', 'adult', 'header', '2017-08-25 17:27:10', NULL, 1),
(8, 'Y''a pas de gênes, là où il y a de l''ADN !', 'all', 'header', '2017-08-25 17:28:44', NULL, 1),
(9, 'Ne confondez pas "eau des WC" et "eau de vaisselle"', 'all', 'header', '2017-08-25 17:29:11', NULL, 1),
(10, 'Les radis c''est pas pour les radins !', 'all', 'header', '2017-08-25 17:30:39', NULL, 1),
(11, 'L''amour c''est comme le pognon, ça va ça vient et quand ça vient ça va !', 'all', 'header', '2017-08-25 17:37:23', NULL, 1),
(12, 'Si tu suis le chemin qui s''appelle "plus tard", tu arriveras à la place qui s''appelle "jamais"', 'all', 'header', '2017-08-25 17:38:12', NULL, 1),
(13, 'Avant Linux, mon ordi plantait tout le temps, je n’avais pas de vie sociale, les filles me fuyaient... maintenant, mon ordi ne plante plus !', 'all', 'paragraph', '2017-08-25 17:39:48', NULL, 1),
(14, 'Les mots de passe sont comme les sous-vêtements. On ne devrait pas les laisser traîner là où des personnes pourraient les voir. On devrait en changer régulièrement. On ne devrait pas les prêter à des inconnus', 'all', 'paragraph', '2017-08-25 17:51:55', NULL, 1),
(15, 'C''est l''histoire d''un pingouin qui respire par les fesses. Un jour il s’assoit et il meurt.', 'adult', 'header', '2017-08-27 10:18:41', '2017-09-04 15:09:30', 3),
(16, 'C''est l''histoire d''un poil. Avant il était bien maintenant il est pubien !', 'adult', 'header', '2017-08-27 10:20:12', '2017-09-04 15:00:16', 3),
(17, 'Certains hommes n''ont que ce qu''ils méritent : les autres sont célibataires.', 'all', 'header', '2017-08-27 10:21:29', NULL, 3),
(18, 'Je ne sais pas ce qui est possible ou non alors j''agis comme si tout est possible. Car est-on certain à 100% que l''on ne peut pas y arriver ? La réponse est non ! La question est donc de savoir si nous sommes ouverts à la possibilité que les choses soient totalement possibles ?', 'all', 'paragraph', '2017-08-29 08:26:47', '2017-09-19 16:25:52', 3),
(19, 'Ne prends pas la suite de ce texte comme une leçon de morale mais comme une question importante que j''ai à te poser et à laquelle je te demande surtout de ne pas me répondre... Est-ce que tu veux aller bien dans la vie ?', 'all', 'paragraph', '2017-08-29 08:30:34', '2017-10-26 15:44:18', 3);
-- --------------------------------------------------------
--
-- Structure de la table `users`
--
CREATE TABLE IF NOT EXISTS `users` (
`user_ID` int(11) NOT NULL,
`user_username` varchar(255) NOT NULL,
`user_password` varchar(255) NOT NULL,
`user_dateCreation` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
--
-- Contenu de la table `users`
--
-- Private content
--
-- Index pour les tables exportées
--
--
-- Index pour la table `jokes`
--
ALTER TABLE `jokes`
ADD PRIMARY KEY (`joke_ID`);
--
-- Index pour la table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_ID`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `jokes`
--
ALTER TABLE `jokes`
MODIFY `joke_ID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT pour la table `users`
--
ALTER TABLE `users`
MODIFY `user_ID` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 6958f62e1abbe7b2af89dfaeefa1795a2cc3b39f | [
"Markdown",
"SQL",
"PHP"
] | 11 | Markdown | eb01/jeanlorem.io | 0e31727a2350d2efaa09d5c8fb6f4e802737fcba | 12f8b7e46af5e70e04e0b271b1dea5f5dfdc3b2a | |
refs/heads/master | <repo_name>lonelydatum/mappingMigration<file_sep>/lib/interaction.js
import Init3d from './init';
var camera = Init3d.camera;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var mouseX = 0;
var mouseXOnMouseDown = 0;
function onTargetRotationChanged(value){
_signals.onTargetRotation.dispatch(value);
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
};
function onDocumentMouseDown( event ) {
event.preventDefault();
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );
document.addEventListener( 'mouseout', onDocumentMouseOut, false );
mouseXOnMouseDown = event.clientX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
};
function onDocumentMouseMove( event ) {
mouseX = event.clientX - windowHalfX;
targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.02;
onTargetRotationChanged(targetRotation)
};
function onDocumentMouseUp( event ) {
document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
document.removeEventListener( 'mouseout', onDocumentMouseOut, false );
};
function onDocumentMouseOut( event ) {
document.removeEventListener( 'mousemove', onDocumentMouseMove, false );
document.removeEventListener( 'mouseup', onDocumentMouseUp, false );
document.removeEventListener( 'mouseout', onDocumentMouseOut, false );
};
function onDocumentTouchStart( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
mouseXOnMouseDown = event.touches[ 0 ].pageX - windowHalfX;
targetRotationOnMouseDown = targetRotation;
}
};
function onDocumentTouchMove( event ) {
if ( event.touches.length == 1 ) {
event.preventDefault();
mouseX = event.touches[ 0 ].pageX - windowHalfX;
targetRotation = targetRotationOnMouseDown + ( mouseX - mouseXOnMouseDown ) * 0.05;
onTargetRotationChanged(targetRotation);
}
};
document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'touchstart', onDocumentTouchStart, false );
document.addEventListener( 'touchmove', onDocumentTouchMove, false );
window.addEventListener( 'resize', onWindowResize, false );
var _signals;
export default function(signals){
_signals = signals;
};
<file_sep>/lib/util/minMaxFamily.js
class MinMaxFamily{
constructor(){
this.
}
}
export default MinMaxFamily;
<file_sep>/README.md
# mappingMigration
Mapping Migration
<file_sep>/config.js
System.config({
"paths": {
"*": "*.js",
"app/*": "lib/*.js",
"github:*": "jspm_packages/github/*.js",
"npm:*": "jspm_packages/npm/*.js"
}
});
System.config({
"meta": {
"jspm_packages/github/mrdoob/three.js@master/build/three": {
"format": "global"
},
"jspm_packages/github/greensock/[email protected]/src/minified/TweenLite.min": {
"format": "global"
},
"jspm_packages/github/greensock/[email protected]/src/minified/easing/EasePack.min": {
"format": "global"
}
}
});
System.config({
"map": {
"TweenLite": "jspm_packages/github/greensock/[email protected]/src/minified/TweenLite.min",
"Easing": "jspm_packages/github/greensock/[email protected]/src/minified/easing/EasePack.min",
"signals": "github:millermedeiros/[email protected]",
"jsonp": "npm:[email protected]",
"stats.js": "github:mrdoob/stats.js@master",
"three": "jspm_packages/github/mrdoob/three.js@master/build/three",
"github:jspm/[email protected]": {
"assert": "npm:[email protected]",
"fs": "github:jspm/[email protected]"
},
"github:jspm/[email protected]": {
"process": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"tty-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"util": "npm:[email protected]"
},
"npm:[email protected]": {
"util": "npm:[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]",
"ms": "npm:[email protected]",
"net": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"tty": "github:jspm/[email protected]",
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"debug": "npm:[email protected]"
},
"npm:[email protected]": {
"inherits": "npm:[email protected]",
"process": "github:jspm/[email protected]"
}
}
});
<file_sep>/lib/util/minMax.js
class MinMax{
constructor(){
this.minX = 999999;
this.maxX = 0;
this.minY = 999999;
this.maxY = 0;
this.family = [];
}
testXY(x,y){
this.minX = (x<this.minX) ? x : this.minX;
this.minY = (y<this.minY) ? y : this.minY;
this.maxX = (x>this.maxX) ? x : this.maxX;
this.maxY = (y>this.maxY) ? y : this.maxY;
this.setCenter();
}
testFamily(minMax){
this.family.push(minMax);
this.family.forEach(item=>{
this.testXY(item.minX, item.minY);
this.testXY(item.maxX, item.maxY);
});
}
setCenter(){
this.width = this.maxX - this.minX;
this.height = this.maxY - this.minY;
this.center = {
x: this.minX + (this.width*.5),
y: this.minY + (this.height*.5)
}
}
}
export default MinMax;
<file_sep>/lib/main.js
import MapController from './map/map_Controller';
import MapView from './map/map_View';
import Interaction from './interaction';
import Init3d from './init';
import Signals from 'signals';
import Asia from './data/asia';
var signals = {
onTargetRotation: new Signals()
}
signals.onTargetRotation.add(function(d){
targetRotation = d;
})
Interaction(signals);
var targetRotation = 0;
var targetRotationOnMouseDown = 0;
var renderer = Init3d.renderer;
var scene = Init3d.scene;
var camera = Init3d.camera;
var group = new THREE.Group();
scene.add( group );
group.rotation.x = Math.PI/180 * -60;
var mapController = new MapController();
var mapView = new MapView(group, mapController);
var helper = new THREE.GridHelper( 80, 10 );
helper.rotation.x = Math.PI / 2;
group.add( helper );
var container = document.getElementById("map");
document.body.appendChild( container );
container.appendChild( renderer.domElement );
var obj = {}
var btn = document.getElementById("tester");
btn.addEventListener("click", function(){
mapController.amountToggle();
}.bind(obj));
function animate() {
requestAnimationFrame( animate );
render();
};
function render() {
group.rotation.z += ( targetRotation - group.rotation.z ) * 0.006;
renderer.render( scene, camera );
};
animate();
export var main = {};<file_sep>/jspm_packages/github/millermedeiros/[email protected]
define(["github:millermedeiros/[email protected]/dist/signals"], function(main) {
return main;
});<file_sep>/lib/map/map_Controller.js
import SvgPoints from '../svgPoints';
import MapItem from './mapItem_Controller';
import Signals from 'signals';
import MinMax from '../util/minMax';
var _signals = {
onAmountChanged: new Signals()
}
class MapController{
constructor(){
this.amount = {
isFuture: null,
isPast: null,
active: 0,
options: ["future", "past"]
}
this.list = [];
this.center = SvgPoints.center;
this.parseData();
}
amountToggle(){
this.amount.active++;
if(this.amount.active%2 == 0){
this.amount.isFuture = true;
this.amount.isPast = false;
}else{
this.amount.isFuture = false;
this.amount.isPast = true;
}
_signals.onAmountChanged.dispatch(this.amount)
}
parseData(){
this.minMax = new MinMax();
SvgPoints.paths.forEach( (dataItem) => {
var mapItem = new MapItem(dataItem, _signals);
this.minMax.testFamily(mapItem.minMax);
this.list.push(mapItem);
});
}
}
export default MapController;
| 34732da495683080a15be7de22b3b4148188864b | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | lonelydatum/mappingMigration | f4d8c4a0fc42172b051982f5c643bca4e3feeed4 | 6533a43e23181655a9d40ff87659683022cf1210 | |
refs/heads/master | <repo_name>lwbldy/GitWork<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/controller/SysRoleController.java
package com.lwbldy.system.controller;
import com.lwbldy.common.util.PageUtils;
import com.lwbldy.common.util.R;
import com.lwbldy.mbg.model.SysRole;
import com.lwbldy.mbg.model.SysUser;
import com.lwbldy.system.service.SysRoleMenuService;
import com.lwbldy.system.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api(tags = "角色管理控制器")
@Controller
public class SysRoleController {
@Autowired
private SysRoleService sysRoleService;
@Autowired
private SysRoleMenuService sysRoleMenuService;
@ApiOperation(value = "跳转到列表")
@GetMapping("sysrole/list")
@RequiresPermissions("sysrole:list")
public String list(){
return "system/sysrole/list";
}
@ApiOperation(value = "分页查询角色")
@PostMapping("sysrole/list")
@ResponseBody
@RequiresPermissions("sysrole:list")
public R list(@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "limit", defaultValue = "15") Integer limit){
List<SysRole> brandList = sysRoleService.listBrand(page,limit);
return PageUtils.restPage(brandList);
}
@ApiOperation(value = "跳转到添加角色页面")
@GetMapping("sysrole/save")
@RequiresPermissions("sysrole:save")
public String save(){
return "system/sysrole/save";
}
@ApiOperation(value = "添加角色")
@PostMapping("sysrole/save")
@ResponseBody
@RequiresPermissions("sysrole:save")
public R save(SysRole sysRole,String roleMenuIds){
int r = sysRoleService.save(sysRole,roleMenuIds);
if(r != 0){
return R.ok("保存成功");
}else{
return R.error("保存失败");
}
}
@RequestMapping("sysrole/fundAll")
@ResponseBody
@ApiOperation(value = "查询所有角色,供用户选择角色")
public R fundAll(){
List list = sysRoleService.queryAll();
return R.ok("成功").put("list",list);
}
@ApiOperation(value="修改角色")
@GetMapping("sysrole/edit/{id}")
@RequiresPermissions("sysrole:edit")
public String edit(@PathVariable("id")long id,ModelMap map){
map.put("id",id);
return "system/sysrole/edit";
}
@ApiOperation(value="修改角色")
@PostMapping("sysrole/edit")
@ResponseBody
@RequiresPermissions("sysrole:edit")
public R edit(SysRole sysRole,String roleMenuIds){
int r = sysRoleService.update(sysRole,roleMenuIds);
if(r != 0){
return R.ok("修改成功");
}else{
return R.error("修改失败");
}
}
@GetMapping("sysrole/delete/{roleId}")
@ResponseBody
@RequiresPermissions("sysrole:delete")
public R delete(@PathVariable("roleId") Long roleId){
int r = sysRoleService.delete(roleId);
if(r != 0){
return R.ok("删除成功");
}else{
return R.error("删除失败");
}
}
/**
* 信息
*/
@RequestMapping("sysrole/info/{roleId}")
@ResponseBody
@RequiresPermissions("sysrole:info")
public R info(@PathVariable("roleId") Long roleId){
SysRole sysRole = sysRoleService.queryById(roleId);
//获取权限菜单
List<Integer> rolMenuList = sysRoleMenuService.queryMenuIdList(roleId);
return R.ok("成功").put("sysRole", sysRole).put("roleList",rolMenuList);
}
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/service/SysRoleMenuService.java
package com.lwbldy.system.service;
import java.util.List;
public interface SysRoleMenuService {
/**
* 保存或更新 角色权限
* @param roleId
* @param menuIdList
*/
void saveOrUpdate(Long roleId, List<Integer> menuIdList);
/**
* 根据角色ID,获取菜单ID列表
* @param roleId
* @return
*/
List<Integer> queryMenuIdList(long roleId);
/**
* 根据 角色ID 删除权限
* @param roleId
* @return
*/
int deleteByRoleId(Long roleId);
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/controller/SysUserController.java
package com.lwbldy.system.controller;
import com.lwbldy.common.shiro.ShiroUtils;
import com.lwbldy.common.util.PageUtils;
import com.lwbldy.common.util.R;
import com.lwbldy.mbg.model.SysUser;
import com.lwbldy.system.service.SysRoleService;
import com.lwbldy.system.service.SysUserRoleService;
import com.lwbldy.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@Api(tags = "系统用户管理控制器")
@Controller
public class SysUserController {
@Autowired
private SysUserService sysUserService;
@Autowired
private SysUserRoleService sysUserRoleService;
@Autowired
private SysRoleService sysRoleService;
@GetMapping("sysuser/list")
@RequiresPermissions("sysuser:list")
public String list(){
return "/system/sysuser/list";
}
@ApiOperation(value = "根据用户名分页查询用户")
@PostMapping("sysuser/list")
@ResponseBody
@RequiresPermissions("sysuser:list")
public R list(@RequestParam(value = "userName", defaultValue = "") String userName,
@RequestParam(value = "page", defaultValue = "1") Integer page,
@RequestParam(value = "limit", defaultValue = "15") Integer limit){
List<SysUser> brandList = sysUserService.listBrand(userName,page,limit);
return PageUtils.restPage(brandList);
}
@ApiOperation(value = "查询用户信息")
@RequestMapping("sysuser/info/{userId}")
@ResponseBody
@RequiresPermissions("sysuser:info")
public R info(@PathVariable("userId") Long userId){
SysUser sysUser = sysUserService.queryByPrimaryKey(userId);
List<Long> roleIds = sysUserRoleService.queryRoleIdList(userId);
return R.ok(sysUser).put("roleIds",roleIds);
}
@ApiOperation(value = "保存用户信息页面")
@GetMapping("sysuser/save")
@RequiresPermissions("sysuser:save")
public String save(ModelMap map){
map.put("roleList",sysRoleService.queryAll());
return "system/sysuser/save";
}
@ApiOperation(value = "保存用户信息")
@RequestMapping("sysuser/save")
@ResponseBody
@RequiresPermissions("sysuser:save")
public R save(SysUser sysUser,String[] roleIds){
List<Long> roleIdList = new ArrayList<>();
if(roleIds != null && roleIds.length!=0){
for(String s:roleIds){
roleIdList.add(Long.parseLong(s));
}
}
int r = sysUserService.save(sysUser,roleIdList);
if(r == 1){
return R.ok("保存成功!");
}else{
return R.error("保存失败!");
}
}
@GetMapping("sysuser/edit/{id}")
@RequiresPermissions("sysuser:edit")
public String update(@PathVariable("id")long id,ModelMap map){
map.put("id",id);
map.put("roleList",sysRoleService.queryAll());
return "system/sysuser/edit";
}
@ApiOperation(value = "修改用户信息")
@RequestMapping("sysuser/edit")
@ResponseBody
@RequiresPermissions("sysuser:edit")
public R update(SysUser sysUser,String[] roleIds){
List<Long> roleIdList = new ArrayList<>();
if(roleIds != null && roleIds.length!=0){
for(String s:roleIds){
roleIdList.add(Long.parseLong(s));
}
}
int r = sysUserService.update(sysUser,roleIdList);
if(r == 1){
return R.ok("修改成功!");
}else{
return R.error("修改失败!");
}
}
@ApiOperation(value = "修改密码")
@RequestMapping("sysuser/changePWD")
@ResponseBody
@RequiresPermissions("sysuser:changePWD")
public R changePWD(long userId,String newPWD){
if (sysUserService.changePWD(userId,newPWD) >= 1){
return R.ok("修改成功");
}else
return R.ok("修改失败");
}
@ApiOperation(value = "修改自己的密码")
@RequestMapping("sysuser/changeMyPWD")
@ResponseBody
public R changeMyPWD(String newPWD){
if (sysUserService.changePWD(ShiroUtils.getUserEntity().getUserId(),newPWD) >= 1){
return R.ok("修改成功");
}else
return R.ok("修改失败");
}
}
<file_sep>/lwb-admin-tiny/README.md
一个简单后台管理
![login](./document/resource/login.jpg)
![admin_index](./document/resource/admin_index.jpg)
![admin_menu](./document/resource/admin_menu.jpg)
![admin_menu_save](./document/resource/admin_menu_save.jpg)
![admin_role_save](./document/resource/admin_role_save.jpg)
![admin_gen](./document/resource/admin_gen.jpg)
使用 Pagehelper 分页
代码生成:
- 配置generatorConfig.xml进行配置表信息
- 执行com.lwbldy.mbg.Generator 生成实体类和mapper文件
- 登录后台点击代码生成,进行配置生成代码拷贝到项目中
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/common/config/ShiroConfig.java
package com.lwbldy.common.config;
import com.lwbldy.common.shiro.MyRealm;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
/**
* 配置进行授权和认证的 Realm,要新增一个java类来实现,下面会有,class=包名.类名,init-methood是初始化的方法
* @return
*/
@Bean("myRealm")
public MyRealm myRealm(){
MyRealm myRealm = new MyRealm();
myRealm.setCredentialMatcher();
return myRealm;
}
/**
* 配置緩存管理器
* @return
*/
@Bean("cacheManager")
public EhCacheManager ehCacheManager(){
EhCacheManager ehCacheManager = new EhCacheManager();
ehCacheManager.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return ehCacheManager;
}
/**
* 配置 SecurityManager Bean.
* @param myRealm
* @param ehCacheManager
* @return
*/
@Bean("securityManager")
public SecurityManager defaultWebSecurityManager(MyRealm myRealm,EhCacheManager ehCacheManager){
DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
defaultWebSecurityManager.setRealm(myRealm);
defaultWebSecurityManager.setCacheManager(ehCacheManager);
return defaultWebSecurityManager;
}
/**
* 配置 ShiroFilter bean: 该 bean 的 id 必须和 web.xml 文件中配置的 shiro filter 的 name 一致
* @return
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//装配 securityManager
shiroFilterFactoryBean.setSecurityManager(securityManager);
//配置登陆页面
shiroFilterFactoryBean.setLoginUrl("/sys/login");
//配置登录成功后的页面
shiroFilterFactoryBean.setSuccessUrl("/sys/index");
//配置未经授权的页面
shiroFilterFactoryBean.setUnauthorizedUrl("/sys/login");
//具体配置需要拦截哪些 URL, 以及访问对应的 URL 时使用 Shiro 的什么 Filter 进行拦截.
shiroFilterFactoryBean.setFilterChainDefinitions(
"/**/*.html = anon\n"+
"/**/*.css = anon\n"+
"/**/*.js = anon\n"+
"/lib/** = anon\n"+
"/sys/login = anon\n"+
"/sys/captcha = anon\n"+
"/sys/checkCaptcha = anon\n"+
"/static/** = anon\n"+
"/** = authc"
);
return shiroFilterFactoryBean;
}
// 加入注解的使用,不加入这个注解不生效
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/controller/SysMenuController.java
package com.lwbldy.system.controller;
import com.alibaba.druid.support.json.JSONUtils;
import com.lwbldy.common.util.R;
import com.lwbldy.mbg.model.SysMenu;
import com.lwbldy.system.service.SysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Api(tags = "菜单管理控制器")
@Controller
public class SysMenuController {
@Autowired
SysMenuService sysMenuService;
@GetMapping("/sysmenu/list")
@RequiresPermissions("sysmenu:list")
public String list(){
return "system/menu/list";
}
@PostMapping("/sysmenu/list")
@ResponseBody
@RequiresPermissions("sysmenu:list")
public R menuList(){
List<SysMenu> list = sysMenuService.listAllSysMenu();
R r = R.ok(list);
r.put("count",list.size());
return r;
}
@ApiOperation(value="跳转到添加保存菜单")
@GetMapping("/sysmenu/save")
@RequiresPermissions("sysmenu:save")
public String save(){
return "system/menu/save";
}
@ApiOperation(value="获取树菜单")
@GetMapping("/sysmenu/findTreeMenu")
@ResponseBody
public R findTreeMenu(){
return R.ok(sysMenuService.queryAllTreeMenu());
}
@ApiOperation(value="保存菜单")
@PostMapping("/sysmenu/save")
@ResponseBody
@RequiresPermissions("sysmenu:save")
public R saveMenu(SysMenu sysMenu){
if(sysMenuService.saveSysMenu(sysMenu) == 1){
return R.ok();
}else
return R.error();
}
@ApiOperation(value="获取菜单实体")
@GetMapping("/sysmenu/info/{id}")
@ResponseBody
@RequiresPermissions("sysmenu:info")
public R info(@PathVariable("id") long id){
SysMenu sysMenu = sysMenuService.queryById(id);
return R.ok().put("sysMenu",sysMenu);
}
@ApiOperation(value="修改菜单")
@GetMapping("/sysmenu/edit/{id}")
@RequiresPermissions("sysmenu:edit")
public String edit(@PathVariable("id")long id,ModelMap map){
map.put("id",id);
return "system/menu/edit";
}
@ApiOperation(value="修改菜单")
@PostMapping("/sysmenu/edit")
@ResponseBody
@RequiresPermissions("sysmenu:edit")
public R edit(SysMenu sysMenu){
int r = sysMenuService.update(sysMenu);
if(r == 1){
return R.ok("修改成功");
}else{
return R.error("修改失败");
}
}
@ApiOperation(value="查询所有菜单提供给角色中的权限树使用")
@GetMapping("/sysmenu/fundAll")
@ResponseBody
public List<SysMenu> fundAll(){
return sysMenuService.listAllSysMenu();
}
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/dao/SysMenuDao.java
package com.lwbldy.system.dao;
import com.lwbldy.mbg.model.SysMenu;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 菜单管理
*/
public interface SysMenuDao{
List<SysMenu> selectMenuByUserId(@Param(value = "userId") Long userId);
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/controller/SysCommonController.java
package com.lwbldy.system.controller;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.lwbldy.common.shiro.ShiroUtils;
import com.lwbldy.common.util.R;
import com.lwbldy.common.util.SessionNames;
import com.lwbldy.mbg.model.SysUser;
import com.lwbldy.system.service.SysMenuService;
import com.lwbldy.system.vo.MenuVO;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.List;
@Api(tags = "系统后台公共登录退出,获取验证码")
@Controller
public class SysCommonController {
@Autowired
private Producer captchaProducer = null;
@Autowired
private SysMenuService sysMenuService;
@ApiOperation(value="后台首页")
@GetMapping({"","/sys/index"})
public String index(){
return "system/index";
}
@ApiOperation(value="欢迎界面")
@GetMapping("sys/welcome")
public String welcome(){
return "system/welcome";
}
@ApiOperation(value="用户登录界面")
@GetMapping("/sys/login")
public String login(){
return "system/login";
}
@ApiOperation(value="用户登录验证")
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名"),
@ApiImplicitParam(name = "password", value = "密码"),
@ApiImplicitParam(name = "vercode", value = "验证码"),
})
@PostMapping("/sys/login")
@ResponseBody
public R loginin(String username, String password, HttpSession session, String vercode) {
try {
if (StringUtils.isNotEmpty(vercode)) {
String original =(String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
// 验证验证码是否成功
if (vercode.equalsIgnoreCase(original)) {
Subject subject = ShiroUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token);
SysUser sysUserEntity = (SysUser) SecurityUtils.getSubject().getPrincipal();
sysUserEntity.setSalt(null);
sysUserEntity.setPassword(<PASSWORD>);
session.setAttribute(SessionNames.ADMIN_SESSION,sysUserEntity);
return R.ok("登录成功!").put("user", sysUserEntity);
}
}
return R.error("验证码错误!");
} catch (UnknownAccountException e) {
e.printStackTrace();
return R.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return R.error("账号或密码不正确");
} catch (LockedAccountException e) {
return R.error("账号已被锁定,请联系管理员");
} catch (AuthenticationException e) {
return R.error("账户验证失败");
}
}
/**
* 生成验证码
* @param request
* @param response
* @throws Exception
*/
@ApiOperation(value="获取图形验证码")
@GetMapping(value = "/sys/captcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
//生成验证码
String capText = captchaProducer.createText();
session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
//向客户端写出
BufferedImage bi = captchaProducer.createImage(capText);
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
}
@ApiOperation(value="退出登录")
@GetMapping(value = "/sys/logout")
public String logout(HttpSession session) {
ShiroUtils.logout();
return "redirect:/";
}
@ApiOperation(value="获取菜单")
@GetMapping(value = "/sys/menu")
@ResponseBody
public MenuVO menuAll(){
SysUser sysUser = ShiroUtils.getUserEntity();
return sysMenuService.queryMenu(sysUser.getUserId());
}
@ApiOperation(value="获取菜单")
@GetMapping(value = "/sys/icon")
public String icon(){
return "system/icon";
}
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/dao/SysUserDao.java
package com.lwbldy.system.dao;
import java.util.List;
public interface SysUserDao {
/**
* 根据用户id查找权限
* @param userId
* @return
*/
List<String> queryAllPerms(Long userId);
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/service/SysRoleService.java
package com.lwbldy.system.service;
import com.lwbldy.mbg.model.SysRole;
import java.util.List;
public interface SysRoleService {
/**
* 根据Id查询角色
* @param id
* @return
*/
SysRole queryById(long id);
/**
* 分页查询角色
* @param pageNum
* @param pageSize
* @return
*/
List<SysRole> listBrand(int pageNum, int pageSize);
/**
* 保存角色
* @param sysRole
* @param roleMenuIds
* @return
*/
int save(SysRole sysRole, String roleMenuIds);
/**
* 更新角色
* @param sysRole
* @param roleMenuIds
* @return
*/
int update(SysRole sysRole, String roleMenuIds);
/**
* 根据id删除目录
* @param roleId
* @return
*/
int delete(Long roleId);
/**
* 查询所有角色
* @return
*/
List<SysRole> queryAll();
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/service/impl/SysRoleServiceImpl.java
package com.lwbldy.system.service.impl;
import com.github.pagehelper.PageHelper;
import com.lwbldy.mbg.mapper.SysRoleMapper;
import com.lwbldy.mbg.model.SysRole;
import com.lwbldy.mbg.model.SysRoleExample;
import com.lwbldy.system.service.SysRoleMenuService;
import com.lwbldy.system.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service("sysRoleService")
public class SysRoleServiceImpl implements SysRoleService {
@Autowired
private SysRoleMapper sysRoleMapper;
@Autowired
SysRoleMenuService sysRoleMenuService;
@Override
public SysRole queryById(long id) {
return sysRoleMapper.selectByPrimaryKey(id);
}
@Override
public List<SysRole> listBrand(int pageNum, int pageSize) {
//开启分页查询
PageHelper.startPage(pageNum, pageSize);
SysRoleExample sysRoleExample = new SysRoleExample();
sysRoleExample.setOrderByClause("role_id desc");
return sysRoleMapper.selectByExample(sysRoleExample);
}
@Override
public int save(SysRole sysRole, String roleMenuIds) {
sysRole.setCreateTime(new Date());
int r = sysRoleMapper.insert(sysRole);
if(r == 0){
return r;
}
System.out.println("roleMenuIds:"+roleMenuIds);
if(roleMenuIds == null || roleMenuIds.length() == 0)
return 1;
String[] roleMenuIdsArr = roleMenuIds.split(",");
List<Integer> roleMenuIdList = new ArrayList<Integer>();
for (String menuId : roleMenuIdsArr){
roleMenuIdList.add(Integer.parseInt(menuId));
}
sysRoleMenuService.saveOrUpdate(sysRole.getRoleId(),roleMenuIdList);
return r;
}
@Override
public int update(SysRole sysRole, String roleMenuIds) {
//先更新
int r = sysRoleMapper.updateByPrimaryKey(sysRole);
if(r == 0){
return r;
}
if(roleMenuIds == null || roleMenuIds.length() == 0)
return 1;
String[] roleMenuIdsArr = roleMenuIds.split(",");
List<Integer> roleMenuIdList = new ArrayList<Integer>();
for (String menuId : roleMenuIdsArr){
roleMenuIdList.add(Integer.parseInt(menuId));
}
sysRoleMenuService.saveOrUpdate(sysRole.getRoleId(),roleMenuIdList);
return r;
}
@Override
public int delete(Long roleId) {
sysRoleMenuService.deleteByRoleId(roleId);
return sysRoleMapper.deleteByPrimaryKey(roleId);
}
@Override
public List<SysRole> queryAll() {
SysRoleExample sysRoleExample = new SysRoleExample();
sysRoleExample.setOrderByClause("role_id desc");
return sysRoleMapper.selectByExample(sysRoleExample);
}
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/dao/SysUserRoleDao.java
package com.lwbldy.system.dao;
import com.lwbldy.mbg.model.SysUserRole;
import java.util.List;
/**
* 用户与角色对应关系
*/
public interface SysUserRoleDao {
/**
* 根据用户ID,获取角色ID列表
*/
List<Long> queryRoleIdList(Long userId);
/**
* 根据用户ID 删除角色
* @param userId 用户ID
* @return
*/
int deleteByUserId(Long userId);
//保存多行数据
int saveBatch(List<SysUserRole> list);
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/vo/MenuVO.java
package com.lwbldy.system.vo;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class MenuVO {
private Long menuId;
private String title;//显示的标题
private String icon;//显示的图标
private String href;//链接
private Long parentId;
private String target = "_self";// 在哪里打开
private List<MenuVO> child;
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/common/shiro/MyRealm.java
package com.lwbldy.common.shiro;
import com.lwbldy.mbg.model.SysMenu;
import com.lwbldy.mbg.model.SysUser;
import com.lwbldy.system.service.SysMenuService;
import com.lwbldy.system.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.*;
/**
* 自定义 拦截器
*/
public class MyRealm extends AuthorizingRealm {
@Autowired
SysUserService sysUserService;
@Autowired
SysMenuService sysMenuService;
/**
* 授权(验证权限时调用)
* @param principals
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SysUser user = (SysUser) principals.getPrimaryPrincipal();
Long userId = user.getUserId();
List<String> permsList = null;
//系统管理员,拥有最高权限
if(userId == 1){
List<SysMenu> menuList = sysMenuService.listAllSysMenu();
permsList = new ArrayList<String>(menuList.size());
//获得所有权限
for(SysMenu menu : menuList){
permsList.add(menu.getPerms());
}
}else {
permsList = sysUserService.queryAllPerms(userId);
}
//用户权限列表
Set<String> permsSet = new HashSet<String>();
for(String perms : permsList){
if(StringUtils.isBlank(perms)){
continue;
}
permsSet.addAll(Arrays.asList(perms.trim().split(",")));
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(permsSet);
return info;
}
/**
* 认证(登录时调用)
* @param authcToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
String userNam = token.getUsername();
SysUser user = sysUserService.queryByName(userNam);
//账号不存在
if(user == null) {
throw new UnknownAccountException("账号或密码不正确");
}
if(user.getStatus() == null || user.getStatus() == 0){
throw new LockedAccountException("用户被锁定");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
return info;
}
//init-method 配置.
public void setCredentialMatcher(){
HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
credentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);//MD5算法加密
credentialsMatcher.setHashIterations(ShiroUtils.hashIterations);//1024次循环加密
setCredentialsMatcher(credentialsMatcher);
}
//用来测试的算出密码password盐值加密后的结果,下面方法用于新增用户添加到数据库操作的,我这里就直接用main获得,直接数据库添加了,省时间
public static void main(String[] args) {
}
@Override
public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
HashedCredentialsMatcher shaCredentialsMatcher = new HashedCredentialsMatcher();
shaCredentialsMatcher.setHashAlgorithmName(ShiroUtils.hashAlgorithmName);
shaCredentialsMatcher.setHashIterations(ShiroUtils.hashIterations);
super.setCredentialsMatcher(shaCredentialsMatcher);
}
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/LwbAdminTinyApplication.java
package com.lwbldy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LwbAdminTinyApplication {
public static void main(String[] args) {
SpringApplication.run(LwbAdminTinyApplication.class, args);
}
}
<file_sep>/lwb-admin-tiny/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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.lwbldy</groupId>
<artifactId>lwb-admin-tiny</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>lwb-admin-tiny</name>
<description>一个可用的简单后台框架,shiro权限管理,自定义代码生成,springboot tomcat 运行,myBatis pagehelper 分页</description>
<properties>
<java.version>1.8</java.version>
<common-version>2.6</common-version>
<pagehelper-version>1.2.10</pagehelper-version>
</properties>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${common-version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${common-version}</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>
<!-- SpringBoot 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot 热编译 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- tomcat jsp 支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- jstl标签库 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--MyBatis分页插件,包含了mybatis-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper-version}</version>
</dependency>
<!-- MyBatis 代码生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.3</version>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!-- 引入druid依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
<!--Swagger-UI API文档生产工具-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<!-- shiro 权限管理 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.3.2</version>
</dependency>
<!-- 验证码 -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<!-- 代码生成器所需jar -->
<dependency>
<artifactId>velocity</artifactId>
<groupId>org.apache.velocity</groupId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>2.0.7.RELEASE</version>
</dependency>
<!-- https://www.hutool.club/ 工具类使用 -->
<!--<dependency>-->
<!--<groupId>cn.hutool</groupId>-->
<!--<artifactId>hutool-all</artifactId>-->
<!--<version>5.1.0</version>-->
<!--</dependency>-->
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<!-- 开启热更新 -->
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
<resources>
<!-- 打包时将jsp文件拷贝到META-INF目录下-->
<resource>
<!-- 指定处理哪个目录下的资源文件 -->
<directory>${basedir}/src/main/webapp</directory>
<!--注意此次必须要放在此目录下才能被访问到-->
<targetPath>META-INF/resources</targetPath>
<includes>
<!-- 所有文件和文件夹 -->
<include>**/**</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/**</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/**.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/service/SysUserService.java
package com.lwbldy.system.service;
import com.github.pagehelper.PageHelper;
import com.lwbldy.mbg.model.SysUser;
import com.lwbldy.mbg.model.SysUserExample;
import org.springframework.util.StringUtils;
import java.util.List;
/**
* 系统用户service
*/
public interface SysUserService {
/**
* 查询用户的所有权限
* @param userId 用户ID
*/
List<String> queryAllPerms(Long userId);
/**
* 根据用户名查询用户信息
* @param name
* @return
*/
SysUser queryByName(String name);
/**
* 按条件分页查询系统用户
* @param userName
* @param pageNum
* @param pageSize
* @return
*/
List<SysUser> listBrand(String userName,int pageNum, int pageSize);
/**
* 根据用户id查询系统用户
* @param userId
* @return
*/
SysUser queryByPrimaryKey(Long userId);
int save(SysUser sysUser,List<Long> roleIds);
int update(SysUser sysUser,List<Long> roleIds);
/**
* 修改密码
* @param userId
* @param newPWD
* @return
*/
int changePWD(long userId,String newPWD);
}
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/system/service/impl/SysUserRoleServiceImpl.java
package com.lwbldy.system.service.impl;
import com.lwbldy.mbg.mapper.SysUserRoleMapper;
import com.lwbldy.mbg.model.SysUserRole;
import com.lwbldy.system.dao.SysUserRoleDao;
import com.lwbldy.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl implements SysUserRoleService {
@Autowired
private SysUserRoleDao sysUserRoleDao;
@Autowired
private SysUserRoleMapper sysUserRoleMapper;
@Override
public void saveOrUpdate(Long userId, List<Long> roleIdList) {
//先删除原来的用户角色
sysUserRoleDao.deleteByUserId(userId);
if(roleIdList == null || roleIdList.size() == 0){
return;
}
//再保存用户角色
List<SysUserRole> sysUserRoles = new ArrayList<SysUserRole>();
for(long roleid : roleIdList){
SysUserRole sysUserRole = new SysUserRole();
sysUserRole.setUserId(userId);
sysUserRole.setRoleId(roleid);
sysUserRoles.add(sysUserRole);
}
sysUserRoleDao.saveBatch(sysUserRoles);
}
@Override
public List<Long> queryRoleIdList(Long userId) {
return sysUserRoleDao.queryRoleIdList(userId);
}
}
<file_sep>/lwb-admin-tiny/document/sql/sql.sql
/*
SQLyog v10.2
MySQL - 5.5.53 : Database - lwbcase
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`lwbcase` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
USE `lwbcase`;
/*Table structure for table `sys_menu` */
DROP TABLE IF EXISTS `sys_menu`;
CREATE TABLE `sys_menu` (
`menu_id` bigint(20) NOT NULL AUTO_INCREMENT,
`parent_id` bigint(20) DEFAULT NULL COMMENT '父菜单ID,一级菜单为0',
`name` varchar(50) DEFAULT NULL COMMENT '菜单名称',
`url` varchar(200) DEFAULT NULL COMMENT '菜单URL',
`perms` varchar(500) DEFAULT NULL COMMENT '授权(多个用逗号分隔,如:user:list,user:create)',
`type` int(11) DEFAULT NULL COMMENT '类型 0:目录 1:菜单 2:按钮',
`icon` varchar(50) DEFAULT NULL COMMENT '菜单图标',
`order_num` int(11) DEFAULT NULL COMMENT '排序',
`tager` varchar(20) DEFAULT NULL COMMENT '打开方式',
PRIMARY KEY (`menu_id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8 COMMENT='菜单管理';
/*Data for the table `sys_menu` */
insert into `sys_menu`(`menu_id`,`parent_id`,`name`,`url`,`perms`,`type`,`icon`,`order_num`,`tager`) values (1,0,'系统管理','','',0,'fa fa-gear',1,''),(2,1,'菜单管理','/sysmenu/list','sysmenu:list',1,'fa fa-user',0,'_self'),(3,2,'添加','','sysmenu:save',2,'',0,NULL),(4,2,'修改','','sysmenu:edit,sysmenu:info',2,'',0,NULL),(5,1,'角色管理','/sysrole/list','sysrole:list',1,'fa fa-users',0,'_self'),(6,1,'用户管理','/sysuser/list','sysuser:list',1,'fa fa-user',0,'_self'),(7,5,'添加','','sysrole:save',2,'',0,'_self'),(8,5,'修改','','sysrole:edit,sysrole:info',2,'',0,'_self'),(9,5,'删除','','sysrole:delete',2,'',0,'_self'),(10,6,'添加','','sysuser:save',2,'',0,'_self'),(11,6,'修改','','sysuser:edit,sysuser:info',2,'',0,'_self'),(12,6,'修改密码','','sysuser:changePWD',2,'',0,'_self'),(28,1,'swagger','/swagger-ui.html','',1,'',0,'_blank'),(29,1,'数据库监控','/druid','',1,'',0,'_blank');
/*Table structure for table `sys_role` */
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`role_id` bigint(20) NOT NULL AUTO_INCREMENT,
`role_name` varchar(100) DEFAULT NULL COMMENT '角色名称',
`remark` varchar(100) DEFAULT NULL COMMENT '备注',
`dept_id` bigint(20) DEFAULT NULL COMMENT '部门ID',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='角色';
/*Data for the table `sys_role` */
/*Table structure for table `sys_role_menu` */
DROP TABLE IF EXISTS `sys_role_menu`;
CREATE TABLE `sys_role_menu` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',
`menu_id` bigint(20) DEFAULT NULL COMMENT '菜单ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8 COMMENT='角色与菜单对应关系';
/*Data for the table `sys_role_menu` */
/*Table structure for table `sys_user` */
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`user_id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL COMMENT '用户名',
`password` varchar(100) DEFAULT NULL COMMENT '密码',
`salt` varchar(20) DEFAULT NULL COMMENT '盐',
`email` varchar(100) DEFAULT NULL COMMENT '邮箱',
`mobile` varchar(100) DEFAULT NULL COMMENT '手机号',
`status` tinyint(4) DEFAULT NULL COMMENT '状态 0:禁用 1:正常',
`dept_id` bigint(20) DEFAULT NULL COMMENT '部门ID',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`user_id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='系统用户';
/*Data for the table `sys_user` */
insert into `sys_user`(`user_id`,`username`,`password`,`salt`,`email`,`mobile`,`status`,`dept_id`,`create_time`) values (1,'admin','<PASSWORD>a<PASSWORD>','<PASSWORD>','<EMAIL>','15070784873',1,1,'2016-11-11 11:11:11');
/*Table structure for table `sys_user_role` */
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
`role_id` bigint(20) DEFAULT NULL COMMENT '角色ID',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COMMENT='用户与角色对应关系';
/*Data for the table `sys_user_role` */
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
<file_sep>/lwb-admin-tiny/src/main/java/com/lwbldy/common/util/SessionNames.java
package com.lwbldy.common.util;
public interface SessionNames {
String ADMIN_SESSION = "adminUser";
}
| 64f34486dd2664e5a4cdcba485bac9f7a172d776 | [
"Markdown",
"Java",
"Maven POM",
"SQL"
] | 20 | Java | lwbldy/GitWork | 750eee733ca25695876a48ebd268a893498b5a84 | c4aa63ea167b235d5f4eecfd1c140b92ba554093 | |
refs/heads/master | <repo_name>managerger/FluentValidation<file_sep>/docs/_doc/mvc5/known-limitations.md
---
title: Known Limitations
---
MVC 5 performs validation in two passes. First it tries to convert the input values from the request into the types declared in your model, and then it performs model-level validation using FluentValidation. If you have non-nullable types in your model (such as `int` or `DateTime`) and there are no values submitted in the request, model-level validations will be skipped, and only the type conversion errors will be returned.
This is a limitation of MVC 5's validation infrastructure, and there is no way to disable this behaviour. If you want all validation failures to be returned in one go, you must ensure that any value types are marked as nullable in your model (you can still enforce non-nullability with a `NotNull` or `NotEmpty` rule as necessary, but the underlying type must allow nulls). This only applies to MVC5 and WebApi 2. ASP.NET Core does not suffer from this issue as the validation infrastructure has been improved.
<file_sep>/docs/_doc/aspnet/aspnet.md
---
title: Getting Started
---
FluentValidation provides built in support for ASP.NET Core, MVC5 and WebApi 2.
Note that support for MVC 5 and WebApi 2 is considered legacy and comes with several limitations. For an optimal experience, we recommend using FluentValidation with ASP.NET Core 2.1 or newer.
For details on using FluentValidation with MVC 5, [click here](/mvc5). For WebApi 2, [click here](/webapi). For ASP.NET Core, read on.<file_sep>/docs/_doc/mvc5.md
---
title: ASP.NET MVC 5 Integration
excerpt: Integration with ASP.NET MVC 5
date: 2019-3-22
icon:
name: icon_globe
color: green
sections:
- /mvc5/getting-started
- /mvc5/known-limitations
- /mvc5/clientside-validation
- /mvc5/manual-validation
- /mvc5/validator-customisation
- /mvc5/validator-interceptors
- /mvc5/rulesets
- /mvc5/ioc
---<file_sep>/src/FluentValidation/TestHelper/TestValidationResult.cs
#region License
// Copyright (c) <NAME> (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://github.com/JeremySkinner/FluentValidation
#endregion
namespace FluentValidation.TestHelper {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using Internal;
using Results;
// TODO: Remove the TValue generic and the IValidationResultTester interface from this for 9.0.
public class TestValidationResult<T, TValue> : ValidationResult, IValidationResultTester where T : class {
[Obsolete("Use properties on the parent class itself")]
public ValidationResult Result { get; private set; }
[Obsolete]
public MemberAccessor<T, TValue> MemberAccessor { get; private set; }
public TestValidationResult(ValidationResult validationResult, MemberAccessor<T, TValue> memberAccessor) : base(validationResult.Errors){
Result = validationResult;
MemberAccessor = memberAccessor;
RuleSetsExecuted = validationResult.RuleSetsExecuted;
}
[Obsolete("Call ShouldHaveValidationError/ShouldNotHaveValidationError instead of Which.ShouldHaveValidationError/Which.ShouldNotHaveValidationError")]
public ITestPropertyChain<TValue> Which {
get {
return new TestPropertyChain<TValue, TValue>(this, Enumerable.Empty<MemberInfo>());
}
}
public IEnumerable<ValidationFailure> ShouldHaveValidationErrorFor<TProperty>(Expression<Func<T, TProperty>> memberAccessor) {
string propertyName = ValidatorOptions.PropertyNameResolver(typeof(T), memberAccessor.GetMember(), memberAccessor);
return ValidationTestExtension.ShouldHaveValidationError(Errors, propertyName, true);
}
public void ShouldNotHaveValidationErrorFor<TProperty>(Expression<Func<T, TProperty>> memberAccessor) {
string propertyName = ValidatorOptions.PropertyNameResolver(typeof(T), memberAccessor.GetMember(), memberAccessor);
ValidationTestExtension.ShouldNotHaveValidationError(Errors, propertyName, true);
}
public IEnumerable<ValidationFailure> ShouldHaveValidationErrorFor(string propertyName) {
return ValidationTestExtension.ShouldHaveValidationError(Errors, propertyName, false);
}
public void ShouldNotHaveValidationErrorFor(string propertyName) {
ValidationTestExtension.ShouldNotHaveValidationError(Errors, propertyName, false);
}
[Obsolete]
IEnumerable<ValidationFailure> IValidationResultTester.ShouldHaveValidationError(IEnumerable<MemberInfo> properties) {
var propertyName = properties.Any() ? GetPropertyName(properties) : ValidationTestExtension.MatchAnyFailure;
return ValidationTestExtension.ShouldHaveValidationError(Errors, propertyName, true);
}
[Obsolete]
void IValidationResultTester.ShouldNotHaveValidationError(IEnumerable<MemberInfo> properties) {
var propertyName = properties.Any() ? GetPropertyName(properties) : ValidationTestExtension.MatchAnyFailure;
ValidationTestExtension.ShouldNotHaveValidationError(Errors, propertyName, true);
}
[Obsolete]
private string GetPropertyName(IEnumerable<MemberInfo> properties) {
var propertiesList = properties.Where(x => x != null).Select(x => x.Name).ToList();
if (MemberAccessor != null) {
string memberName = ValidatorOptions.PropertyNameResolver(typeof(T), MemberAccessor.Member, MemberAccessor);
if (!string.IsNullOrEmpty(memberName)) {
propertiesList.Insert(0, memberName);
}
}
return string.Join(".", propertiesList);
}
}
}
<file_sep>/docs/_doc/aspnet.md
---
title: ASP.NET Integration
excerpt: Integration with ASP.NET Core, ASP.NET MVC 5 and ASP.NET WebApi 2
date: 2018-12-1
icon:
name: icon_globe
color: green
sections:
- /aspnet/aspnet
- /aspnet/core
---<file_sep>/docs/_doc/mvc5/validator-interceptors.md
---
title: Validator Interceptors
---
You can further customize this process by using an interceptor. An interceptor has to implement the IValidatorInterceptor interface from the FluentValidation.Mvc namespace:
```csharp
public interface IValidatorInterceptor {
ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext);
ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result);
}
```
This interface has two methods – BeforeMvcValidation and AfterMvcValidation. If you implement this interface in your validator classes then these methods will be called as appropriate during the MVC validation pipeline.
BeforeMvcValidation is invoked after the appropriate validator has been selected but before it is invoked. One of the arguments passed to this method is a ValidationContext that will eventually be passed to the validator. The context has several properties including a reference to the object being validated. If we want to change which rules are going to be invoked (for example, by using a custom ValidatorSelector) then we can create a new ValidationContext, set its Selector property, and return that from the BeforeMvcValidation method.
Likewise, AfterMvcValidation occurs after validation has occurs. This time, we also have a reference to the result of the validation. Here we can do some additional processing on the error messages before they’re added to modelstate.
As well as implementing this interface directly in a validator class, we can also implement it externally, and specify the interceptor by using a CustomizeValidatorAttribute on an action method parameter:
```csharp
public ActionResult Save([CustomizeValidator(Interceptor=typeof(MyCustomerInterceptor))] Customer cust) {
//...
}
```
In this case, the interceptor has to be a class that implements IValidatorInterceptor and has a public, parameterless constructor. The advantage of this approach is that your validators don’t have to be in an assembly that directly references System.Web.Mvc.
Note that this is considered to be an advanced scenario. Most of the time you probably won’t need to use an interceptor, but the option is there if you want it.
<file_sep>/docs/_doc/mvc5/rulesets.md
---
title: Specifying a RuleSet for client-side messages
---
If you’re using rulesets alongside ASP.NET MVC, then you’ll notice that by default FluentValidation will only generate client-side error messages for rules not part of any ruleset. You can instead specify that FluentValidation should generate clientside rules from a particular ruleset by attributing your controller action with a RuleSetForClientSideMessagesAttribute:
```csharp
[RuleSetForClientSideMessages("MyRuleset")]
public ActionResult Index() {
return View(new PersonViewModel());
}
```
You can also use the `SetRulesetForClientsideMessages` extension method within your controller action (you must have the FluentValidation.Mvc namespace imported):
```csharp
public ActionResult Index() {
ControllerContext.SetRulesetForClientsideMessages("MyRuleset");
return View(new PersonViewModel());
}
```
<file_sep>/docs/_doc/mvc5/manual-validation.md
---
title: Manual Validation
---
Sometimes you may want to manually validate an object in a MVC project. In this case, the validation results can be copied to MVC's modelstate dictionary:
```csharp
public ActionResult DoSomething() {
var customer = new Customer();
var validator = new CustomerValidator();
var results = validator.Validate(customer);
results.AddToModelState(ModelState, null);
return View();
}
```
The AddToModelState method is implemented as an extension method, and requires a using statement for the FluentValidation namespace. Note that the second parameter is an optional model name, which will cause property names in the ModelState to be prefixed (eg a call to AddToModelState(ModelState, "Foo") will generate property names of "Foo.Id" and "Foo.Name" etc rather than just "Id" or "Name")
<file_sep>/docs/_doc/mvc5/getting-started.md
---
title: Getting Started
---
<div class="callout-block callout-info"><div class="icon-holder" markdown="1">* *{: .fa .fa-info-circle}
</div><div class="content" markdown="1">
{: .callout-title}
#### Deprecation Notice
Integration with ASP.NET MVC 5 is considered legacy and will not be supported beyond FluentValidation 8.x.
For an optimal experience, we suggest using FluentValidtation with [ASP.NET Core](/aspnet).
</div></div>
FluentValidation can be configured to work with ASP.NET MVC 5 projects.
To enable MVC integration, you'll need to add a reference to the `FluentValidation.Mvc5` assembly from the appropriate NuGet package:
```shell
Install-Package FluentValidation.Mvc5
```
Once installed, you'll need to configure the `FluentValidationModelValidatorProvider` (which lives in the FluentValidation.Mvc namespace) during the `Application_Start` event of your MVC application, which is in your Global.asax.
```csharp
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
FluentValidationModelValidatorProvider.Configure();
}
```
Internally, FluentValidation's MVC integration makes use of a *validator factory* to know how to determine which validator should be used to validate a particular type. By default, FluentValidation ships with an AttributedValidatorFactory that allows you to link a validator to the type that it validates by decorating the class to validate with an attribute that identifies its corresponding validator:
```csharp
[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
```
Instead of using an attribute, you can also use a custom validator factory with an IoC container. You can tell the `FluentValidationModelValidatorProvider` to use a different validator factory by passing a nested closure into the `Configure` method which allows the provider to be customized:
```csharp
FluentValidationModelValidatorProvider.Configure(provider => {
provider.ValidatorFactory = new MyCustomValidatorFactory();
});
```
Finally, we can create the controller and associated view:
```csharp
public class PeopleController : Controller {
public ActionResult Create() {
return View();
}
[HttpPost]
public ActionResult Create(Person person) {
if(! ModelState.IsValid) { // re-render the view when validation failed.
return View("Create", person);
}
TempData["notice"] = "Person successfully created";
return RedirectToAction("Index");
}
}
```
...and here's the corresponding view (using Razor):
```html
@Html.ValidationSummary()
@using (Html.BeginForm()) {
Id: @Html.TextBoxFor(x => x.Id) @Html.ValidationMessageFor(x => x.Id)
<br />
Name: @Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
Email: @Html.TextBoxFor(x => x.Email) @Html.ValidationMessageFor(x => x.Email)
<br />
Age: @Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<br /><br />
<input type="submit" value="submit" />
}
```
Now when you post the form MVC’s `DefaultModelBinder` will validate the Person object using the `FluentValidationModelValidatorProvider`.
*Note for advanced users* When validators are executed using this automatic integration, the [RootContextData](/start.html#root-context-data) contain an entry called `InvokedByMvc` with a value set to true, which can be used within custom validators to tell whether a validator was invoked automatically by MVC, or manually.
<file_sep>/docs/_doc/webapi/manual-validation.md
---
title: Manual Validation
---
Sometimes you may want to manually validate an object in a WebApi project. In this case, the validation results can be copied to MVC's modelstate dictionary:
```csharp
public IHttpActionResult DoSomething() {
var customer = new Customer();
var validator = new CustomerValidator();
var results = validator.Validate(customer);
results.AddToModelState(ModelState, null);
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
```
The `AddToModelState` method is implemented as an extension method, and requires a using statement for the `FluentValidation.WebApi` namespace. Note that the second parameter is an optional model name, which will cause property names in the ModelState to be prefixed (eg a call to AddToModelState(ModelState, "Foo") will generate property names of "Foo.Id" and "Foo.Name" etc rather than just "Id" or "Name")
<file_sep>/docs/_doc/mvc5/validator-customisation.md
---
title: Validator Customisation
---
The downside of using this automatic integration is that you don’t have access to the validator directly which means that you don’t have as much control over the validation processes compared to running the validator manually.
You can use the CustomizeValidatorAttribute to configure how the validator will be run. For example, if you want the validator to only run for a particular ruleset then you can specify that ruleset name by attributing the parameter that is going to be validated:
```csharp
public ActionResult Save([CustomizeValidator(RuleSet="MyRuleset")] Customer cust) {
// ...
}
```
This is the equivalent of specifying the ruleset if you were to pass a ruleset name to a validator:
```csharp
var validator = new CustomerValidator();
var customer = new Customer();
var result = validator.Validate(customer, ruleSet: "MyRuleset");
```
The attribute can also be used to invoke validation for individual properties:
```csharp
public ActionResult Save([CustomizeValidator(Properties="Surname,Forename")] Customer cust) {
// ...
}
```
…which would be the equivalent of specifying properties in the call to validator.Validate:
```csharp
var validator = new CustomerValidator();
var customer = new Customer();
var result = validator.Validate(customer, properties: new[] { "Surname", "Forename" });
```
You can also use the CustomizeValidatorAttribute to skip validation for a particular type. This is useful for if you need to validate a type manually (for example, if you want to perform async validation then you'll need to instantiate the validator manually and call ValidateAsync as MVC's validation pipeline is not asynchronous).
```csharp
public ActionResult Save([CustomizeValidator(Skip=true)] Customer cust) {
// ...
}
```
<file_sep>/docs/_doc/mvc5/ioc.md
---
title: Using an Inversion of Control Container
---
When using FluentValidation's ASP.NET MVC 5 integration you may wish to use an Inversion of Control container to instantiate your validators rather than relying on the attribute based approach. This can be achieved by writing a custom Validator Factory.
The IValidatorFactory interface defines the contract for validator factories.
```csharp
public interface IValidatorFactory {
IValidator<T> GetValidator<T>();
IValidator GetValidator(Type type);
}
```
Instead of implementing this interface directly, you can inherit from the `ValidatorFactoryBase` class which does most of the work for you. When you inherit from ValidatorFactoryBase you should override the `CreateInstance` method. In this method you should call in to your IoC container to resolve an instance of the specified type or return `null` if it does not exist (many containers have a "TryResolve" method that will do this automatically).
Once you've implemented this interface, you can set the `ValidatorFactory` of the provider during application startup:
```csharp
FluentValidationModelValidatorProvider.Configure(cfg => {
cfg.ValidatorFactory = new MyValidatorFactory();
});
```<file_sep>/docs/_doc/webapi.md
---
title: ASP.NET WebApi 2 integration
excerpt: Integration with ASP.NET WebApi 2
date: 2019-3-22
icon:
name: icon_globe
color: green
sections:
- /webapi/getting-started
- /webapi/manual-validation
- /webapi/validator-customization
- /webapi/validator-interceptors
- /webapi/ioc
---<file_sep>/docs/_doc/webapi/getting-started.md
---
title: Getting Started
---
<div class="callout-block callout-info"><div class="icon-holder" markdown="1">* *{: .fa .fa-info-circle}
</div><div class="content" markdown="1">
{: .callout-title}
#### Deprecation Notice
Integration with ASP.NET WebApi 2 is considered legacy and will not be supported beyond FluentValidation 8.x.
For an optimal experience, we suggest using FluentValidtation with [ASP.NET Core](/aspnet).
</div></div>
FluentValidation can be configured to work with WebApi 2 projects. To enable WebApi integration, you'll need to add a reference to the `FluentValidation.WebApi` assembly from the appropriate NuGet package:
```shell
Install-Package FluentValidation.WebApi
```
Once installed, you'll need to configure the `FluentValidationModelValidatorProvider` (which lives in the `FluentValidation.WebApi` namespace) during your application's startup routine. This is usually inside the `Register` method of your `WebApiConfig` class which can be found in the App_Start directory.
```csharp
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
FluentValidationModelValidatorProvider.Configure(config);
}
```
If you are self-hosting with OWIN, then this should instead be inside your OWIN startup class's `Configuration` method:
```csharp
public class Startup {
public void Configuration(IAppBuilder appBuilder) {
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
FluentValidationModelValidatorProvider.Configure(config);
appBuilder.UseWebApi(config);
}
}
```
Internally, FluentValidation's WebApi integration makes use of a *validator factory* to determine which validator should be used to validate a particular type. By default, FluentValidation ships with an AttributedValidatorFactory that allows you to link a validator to the type that it validates by decorating the class to validate with an attribute that identifies its corresponding validator:
```csharp
[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}
```
Instead of using an attribute, you can also use a custom validator factory with an IoC container. You can tell the `FluentValidationModelValidatorProvider` to use a different validator factory by passing a nested closure into the `Configure` method which allows the provider to be customized:
```csharp
FluentValidationModelValidatorProvider.Configure(config, provider => {
provider.ValidatorFactory = new MyCustomValidatorFactory();
});
```
Finally, we can create the controller:
```csharp
public class PeopleController : ApiController {
[HttpPost]
public IHttpActionResult Create(Person person) {
if(! ModelState.IsValid) { // re-render the view when validation failed.
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
}
```
Now when you post data to the controller's `Create` method (for example, as JSON) then WebApi will automatically call into FluentValidation to find the corresponding validator. Any validation failures will be stored in the controller's `ModelState` dictionary which can be used to generate an error response which can be returned to the client.
*Note for advanced users* When validators are executed using this automatic integration, the [RootContextData](/start.html#root-context-data) contain an entry called `InvokedByWebApi` with a value set to true, which can be used within custom validators to tell whether a validator was invoked automatically by WebApi, or manually.
<file_sep>/docs/_doc/mvc5/clientside-validation.md
---
title: Clientside Validation
---
Note that FluentValidation will also work with ASP.NET MVC's client-side validation, but not all rules are supported. For example, any rules defined using a condition (with When/Unless), custom validators, or calls to Must will not run on the client side. The following validators are supported on the client:
* NotNull/NotEmpty
* Matches (regex)
* InclusiveBetween (range)
* CreditCard
* Email
* EqualTo (cross-property equality comparison)
* Length
| e1f60ee47d6b41c0a5ecc4286a6c35d7b05a6bfe | [
"Markdown",
"C#"
] | 15 | Markdown | managerger/FluentValidation | 2c6a6f15ce67212185c0a2f4d12812f4e1ff1422 | 49125f57a752735e41ee029e5ab4e8d29085d1ea | |
refs/heads/master | <repo_name>zccmark/pcart<file_sep>/application/models/Staff_model.php
<?php
class Staff_model extends MY_Model
{
public $table = 'staff';
public $primary_key = 'stId';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
$this->has_one['retail'] = array('foreign_model' => 'Retail_model', 'foreign_table' => 'retail', 'foreign_key' => 'rId', 'local_key' => 'rId_link');
$this->has_one['country'] = array('foreign_model' => 'Country_model', 'foreign_table' => 'country', 'foreign_key' => 'cyId', 'local_key' => 'cyId_link');
$this->has_one['area'] = array('foreign_model' => 'Area_model', 'foreign_table' => 'area', 'foreign_key' => 'aaId', 'local_key' => 'aaId_link');
}
}
?>
<file_sep>/application/views/coupon/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">貴賓優惠券序號登錄</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>優惠券張數</label>
<input type="number" name="qty" class="form-control text-right" required />
</div>
<div class="form-group">
<label>首張優惠券序號</label>
<input name="first_couponNum" class="form-control" value="" />
</div>
<div class="form-group">
<label>末張優惠券序號</label>
<input name="last_couponNum" class="form-control" value="" />
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/coupon/overview')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/stock_counting/edit.php
<div class="container">
<h1 class="mb-4 text-center">盤盈虧報表編輯</h1>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">盤點事由</label>
<div class="col-sm-10">
<?= $counting_reason ?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">承辦人</label>
<div class="col-sm-10">
<?= $dealer['name'] ?>
</div>
</div>
<form method="post" id="countingForm" enctype="multipart/form-data">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號<br />貨品名稱</th>
<th>盤點內容</th>
</tr>
<?php if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr class="<?= ($product['pKind'] == '3') ? ' olive_bg' : '' ?>">
<td class="text-center"><?= $i ?></td>
<td>
<?= $product['p_num'] ?><br />
<?= $product['pdName'] ?> <?= $product['intro2'] ?>
</td>
<td>
<table class="table table-hover table-bordered">
<tr>
<th class="text-right">原數量</th>
<th>到期日</th>
<th class="text-right">數量</th>
<th>盤點盈虧</th>
<th style="width: 300px;">盤差說明</th>
<th>附件</th>
</tr>
<?php
if ($product['stocks']){
foreach ($product['stocks'] as $k => $s) {
?>
<tr class="product_stock">
<td class="text-right product_stock_original"><?= $s['stock'] ?></td>
<td>
<input type="date" name="items[<?= $product_id ?>][<?= $k ?>][date]"
class="item_date form-control"
value="<?= set_value('items[' . $product_id . '][' . $k . '][date]', $s['expired_at']) ?>"
style="width: 200px;"
/>
</td>
<td>
<input type="number" name="items[<?= $product_id ?>][<?= $k ?>][qty]"
min="0" class="item_qty form-control text-right"
data-stock="<?= $s['stock'] ?>"
value="<?= set_value('items[' . $product_id . '][' . $k . '][qty]', $s['stock']) ?>"
style="width: 120px;"
/>
</td>
<td class="item_diff text-right"></td>
<td>
<div class="input-group">
<?php
echo form_dropdown('items[' . $product_id . '][' . $k . '][diff_reason]', $diff_reason, '', 'class="item_diff_reason form-control" disabled');
?>
<input name="items[<?= $product_id ?>][<?= $k ?>][diff_reason_text]"
maxlength="200"
class="item_diff_reason_text form-control d-none" disabled
required value="" placeholder="盤差說明"/>
</div>
</td>
<td>
<input type="file" class="input_diff_files form-control-file" disabled
name="diff_files[<?= $product_id ?>][<?= $k ?>]"
style="min-width: 120px;"/>
</td>
</tr>
<?php
}
} else {
$k = 0;
?>
<tr class="product_stock">
<td class="text-right product_stock_original">0</td>
<td>
<input type="date" name="items[<?= $product_id ?>][<?= $k ?>][date]"
class="item_date form-control"
value="<?= set_value('items[' . $product_id . '][' . $k . '][date]') ?>"
style="width: 200px;"
/>
</td>
<td>
<input type="number" name="items[<?= $product_id ?>][<?= $k ?>][qty]"
min="0" class="item_qty form-control text-right"
data-stock="0"
value="<?= set_value('items[' . $product_id . '][' . $k . '][qty]') ?>"
style="width: 120px;"
/>
</td>
<td class="item_diff text-right"></td>
<td>
<div class="input-group">
<?php
echo form_dropdown('items[' . $product_id . '][' . $k . '][diff_reason]', $diff_reason, '', 'class="item_diff_reason form-control" disabled');
?>
<input name="items[<?= $product_id ?>][<?= $k ?>][diff_reason_text]"
maxlength="200"
class="item_diff_reason_text form-control d-none" disabled
required value="" placeholder="盤差說明"/>
</div>
</td>
<td>
<input type="file" class="input_diff_files form-control-file" disabled
name="diff_files[<?= $product_id ?>][<?= $k ?>]"
style="min-width: 120px;"/>
</td>
</tr>
<?php
}
?>
<tr class="product_stock_add">
<td colspan="6">
<input type="button" class="btn btn-warning btn-add-expired"
data-product="<?= $product_id ?>" data-index="<?= $k ?>"
value="新增到期日"/>
</td>
</tr>
</table>
</td>
</tr>
<?php
$i++;
}
}
?>
</table>
<div class="form-group text-center">
<input type="submit" name="submit_cancel" class="btn btn-warning mr-2" value="取消│不儲存"/>
<input type="submit" name="submit_save" class="btn btn-success" value="新增完成│儲存送出"/>
</div>
</form>
</div>
<script>
$().ready(function () {
$('.btn-add-expired').on('click', function(){
var index = $(this).data('index') + 1;
var product_id = $(this).data('product');
$(this).data('index', index);
var html = $(this).parents('tr.product_stock_add').prev().clone();
html.find('td.product_stock_original').text('');
html.find('input.item_date').prop('name', 'items[' + product_id + '][' + index + '][date]').val('');
html.find('input.item_qty').prop('name', 'items[' + product_id + '][' + index + '][qty]').val('').data('stock', 0);
html.find('select.item_diff_reason').prop('name', 'items[' + product_id + '][' + index + '][diff_reason]').prop('selected', false);
html.find('input.input_diff_files').prop('name', 'diff_files[' + product_id + '][' + index + ']').val('');
$(this).parents('tr.product_stock_add').before(html);
$(this).parents('tr.product_stock_add').prev().find('input.item_qty').trigger('change');
});
$(document).on('change',"input.item_qty",function () {
var qty = parseInt($(this).val()) || 0;
var stock = parseInt($(this).data('stock')) || 0;
$(this).parents('tr.product_stock').find('.item_diff').text((qty - stock));
if (qty == stock){
$(this).parents('tr.product_stock').find('.item_diff_reason').val('').prop('disabled', true);
$(this).parents('tr.product_stock').find('.item_diff_reason_text').addClass('d-none').val('').prop('disabled', true);
$(this).parents('tr.product_stock').find('.input_diff_files').val('').prop('disabled', true);
} else {
$(this).parents('tr.product_stock').find('.item_diff_reason').prop('disabled', false);
$(this).parents('tr.product_stock').find('.item_diff_reason_text').prop('disabled', false);
$(this).parents('tr.product_stock').find('.input_diff_files').prop('disabled', false);
}
});
$('.item_diff_reason').change(function () {
var item_diff_reason = parseInt($(this).val());
if (item_diff_reason == 2) {
$(this).next().val('').prop('disabled', false).removeClass('d-none');
} else {
$(this).next().val('').prop('disabled', true).addClass('d-none');
}
});
$("#countingForm").find('input[type="submit"]').click(function (e) {
$.each($('.item_date'), function(){
if ($(this).val() == ''){
$(this).prop('disabled', true);
}
});
$.each($('.item_qty'), function(){
if ($(this).val() == ''){
$(this).prop('disabled', true);
}
});
$.each($('.item_diff_reason'), function(){
if ($(this).val() == ''){
$(this).prop('disabled', true);
}
});
$.each($('.item_diff_reason_text'), function(){
if ($(this).val() == ''){
$(this).prop('disabled', true);
}
});
$.each($('.input_diff_files'), function(){
if ($(this).val() == ''){
$(this).prop('disabled', true);
}
});
});
});
</script><file_sep>/application/views/commission/dealers.php
<div class="container">
<button type="button" class="btn btn-success float-right" data-toggle="modal" data-target="#salesModal">
輔銷人定義
</button>
<h1 class="mb-4">輔銷人名單</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">經銷單位</th>
<th class="text-center">輔銷單位</th>
<th class="text-center">輔銷人</th>
<th class="text-center">輔銷人獎金</th>
</tr>
<?php
if ($retailers) {
foreach ($retailers as $retailer) {
?>
<tr>
<td class="text-center"><?= $retailer['company'] ?></td>
<td class="text-center"><?= empty($retailer['sales_retailer']) ? '' : $retailer['sales_retailer']['company'] ?></td>
<td class="text-center"><?= empty($retailer['sales_dealer']) ? '' : $retailer['sales_dealer']['name'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if ($retailer['sales_dealer_id'] && !empty($authority['dealer'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/commission/dealer/' . $retailer['sales_dealer_id']) ?>">明細</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="4" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="modal fade" id="salesModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">輔銷人定義</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>輔銷人:開發引介經銷商之輔銷單位人員(即員工或股東)或經銷商;即經銷商首次登錄時所用帳密的所有人。”</p>
<p>輔銷人為經銷商時,「輔銷單位」為「總經銷」;輔銷人非經銷商、即為「皮瑪斯門市(或總經銷) 」之「人員或股東」時,輔銷單位為「皮瑪斯門市」或「總經銷」。但經銷櫃位B、及全部之經銷店面之「輔銷單位」為「總經銷」。</p>
<p>輔銷人之輔導金,由輔銷單位發放。</p>
</div>
</div>
</div>
</div><file_sep>/application/views/payment/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增付款紀錄</h1>
<form method="post" enctype="multipart/form-data">
<?php if ($error) { ?>
<div class="alert alert-danger">
<?= implode('<br>', $error) ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">付款金額</label>
<div>
$<?=number_format($payment['price'])?>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">付款單位</label>
<div><?=$payment['paid_retailer']['company']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">收款單位</label>
<div><?=$payment['received_retailer']['company']?></div>
</div>
<div id="bank_info" class="d-none">
<div class="form-group">
<label class="font-weight-bold">收款銀行</label>
<div><?=$payment['received_retailer']['bank']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">分行名</label>
<div><?=$payment['received_retailer']['bank_branch']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">收款戶名</label>
<div><?=$payment['received_retailer']['bank_account_title']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">收款帳戶</label>
<div><?=$payment['received_retailer']['bank_account']?></div>
</div>
</div>
<div class="form-group">
<label>付款方式</label>
<?php
echo form_dropdown('type_id', paymentType(), set_value('type_id'), 'id="payment_type" class="form-control"');
?>
</div>
<div class="form-group" id="receipt_wrap">
<label class="font-weight-bold">上傳付款憑證</label>
<input type="file" class="form-control-file" name="receipt" required />
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/payment/overview')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="送出已付款訊息"/>
</div>
</form>
</div>
</div>
</div>
<script>
$().ready(function () {
$('#payment_type').change(function(){
if ($(this).val() == '2'){ //匯款
$('#receipt_wrap').removeClass('d-none').find('input[name="receipt"]').prop('required', true);
$('#bank_info').removeClass('d-none');
} else {
$('#receipt_wrap').addClass('d-none').find('input[name="receipt"]').prop('required', false);
$('#bank_info').addClass('d-none');
}
});
$('#payment_type').trigger('change');
});
</script><file_sep>/application/controllers/Supervisor.php
<?php
class Supervisor extends MY_Controller
{
protected $dealer;
public $threshold_categories;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('retailer_relationship_model');
$this->load->model('retailer_level_model');
$this->load->model('purchase_model');
$this->load->model('shipment_model');
$this->load->library('purchase_lib');
$this->threshold_categories = [
1 => '未達門檻之經銷商',
2 => '已達門檻之經銷商',
3 => '超過門檻之經銷商',
];
$this->session->set_userdata('return_page', base_url('/supervisor/overview'));
}
public function overview()
{
$sales_retailer_select = [];
$sales_dealer_select = [];
if ($this->dealer['retailer_role_id'] == 2){
$_retailers = $this->retailer_model
->with_sales_retailer()
->with_sales_dealer(['with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('sales_retailer_id IS NOT NULL', null, null, false, false, true)
->where('sales_dealer_id IS NOT NULL', null, null, false, false, true)
->get_all();
if ($_retailers){
foreach ($_retailers as $r){
$sales_retailer_select[$r['sales_retailer_id']] = $r['sales_retailer']['company'];
$sales_dealer_select[$r['sales_dealer_id']] = '(' . $r['sales_dealer']['retailer']['company'] . ')' . $r['sales_dealer']['name'];
}
}
}
$sales_retailer_id = (int)$this->input->get('sales_retailer_id');
if (!$sales_retailer_id || empty($sales_retailer_select[$sales_retailer_id])){
$sales_retailer_id = null;
}
$sales_dealer_id = (int)$this->input->get('sales_dealer_id');
if (!$sales_dealer_id || empty($sales_dealer_select[$sales_dealer_id])){
$sales_dealer_id = null;
}
$year = (int)$this->input->get('year');
$month = (int)$this->input->get('month');
$year = $year ? $year : date('Y');
$month = $month ? $month : date('m');
$retailer_level_selects = $this->retailer_level_model->getLevelSelect();
$retailer_level_id = (int)$this->input->get('retailer_level_id');
if (!$retailer_level_id || empty($retailer_level_selects[$retailer_level_id])){
$retailer_level_id = null;
}
$threshold_category = (int)$this->input->get('threshold_category');
if (!$threshold_category || empty($this->threshold_categories[$threshold_category])){
$threshold_category = null;
}
$disabled = 0;
if (!empty($this->input->get('disabled'))){
$disabled = 1;
}
$search = array(
'year' => $year,
'month' => $month,
'retailer_level_id' => $retailer_level_id,
'threshold_category' => $threshold_category,
'sales_retailer_id' => $sales_retailer_id,
'sales_dealer_id' => $sales_dealer_id,
'disabled' => $disabled,
);
$retailers = [];
$pagination = '';
$_relationships = $this->retailer_relationship_model
->where('relation_type', 'supervisor')
->where('relation_retailer_id', $this->dealer['retailer_id'])
->get_all();
if ($_relationships){
$relationship_ids = [];
foreach ($_relationships as $relationship){
array_push($relationship_ids, $relationship['retailer_id']);
}
if ($relationship_ids){
if ($search['retailer_level_id']){
$this->retailer_model->where('retailer_level_id', $search['retailer_level_id']);
}
$next_month_first_day = date('Y-m-d', strtotime('first day of next month ' . $search['year'] . '-' . $search['month'] . '-1'));
$total_retailers_count = $this->retailer_model
->where('id', $relationship_ids)
->where('created_at', '<', $next_month_first_day)
->count_rows();
if ($search['retailer_level_id']){
$this->retailer_model->where('retailer_level_id', $search['retailer_level_id']);
}
if ($search['disabled']){
$this->retailer_model->where('disabled_at IS NOT NULL', null, null, false, false, true);
} else {
$this->retailer_model->where('disabled_at IS NULL', null, null, false, false, true);
}
$_retailers = $this->retailer_model
->with_sales_retailer()
->with_sales_dealer()
->with_role()
->with_level(['with' => ['relation' => 'type']])
->where('id', $relationship_ids)
->where('created_at', '<', $next_month_first_day)
->paginate(20, $total_retailers_count);
if ($_retailers){
foreach ($_retailers as $retailer) {
if ($search['sales_retailer_id'] && $search['sales_retailer_id'] != $retailer['sales_retailer_id']){
continue;
}
if ($search['sales_dealer_id'] && $search['sales_dealer_id'] != $retailer['sales_dealer_id']){
continue;
}
$retailer_total_purchases = $this->purchase_lib->getRetailerTotalPurchases($retailer['id'], $next_month_first_day);
$first_total = $retailer_total_purchases['first_total'];
$first_at = $retailer_total_purchases['first_at'];
$total = $retailer_total_purchases['total'];
if (!$first_at){
continue;
}
if (empty($retailer['level'])) {
$retailer['level_title'] = $retailer['role']['title'];
$retailer['threshold'] = $retailer['purchaseThreshold'];
} else {
$retailer['level_title'] = $retailer['level']['type']['title'] . ' ' . $retailer['level']['code'];
$retailer['threshold'] = $retailer['purchaseThreshold'] ? $retailer['purchaseThreshold'] : $retailer['level']['monthThreshold'];
}
$first_month_diff = $this->purchase_lib->get_month_diff($first_at, $next_month_first_day);
$retailer['first'] = false;
$retailer['under'] = 0;
$retailer['over'] = 0;
$retailer['total'] = 0;
$table = $this->purchase_model->get_table_name();
$search_total_purchases = $this->purchase_model
->fields('SUM(' . $table . '.subtotal) as total')
->where('YEAR(created_at) = "' . $search['year'] . '"', null, null, false, false, true)
->where('MONTH(created_at) = "' . $search['month'] . '"', null, null, false, false, true)
->where('retailer_id', $retailer['id'])
->where('isConfirmed', 1)
->get();
if ($search_total_purchases) {
$retailer['total'] = $search_total_purchases['total'] ? $search_total_purchases['total'] : 0;
}
if ($first_month_diff == 1){
$retailer['first'] = true;
$retailer['under'] = 0;
$retailer['over'] = $retailer['total'] - $first_total - $retailer['threshold'];
if ($retailer['over'] < 0) {
$retailer['over'] = 0;
}
} else {
$search_diff = $total - $first_total - $retailer['threshold'] * $first_month_diff;
if ($search_diff < 0) {
$retailer['under'] = abs($search_diff);
if ($retailer['under'] > $retailer['threshold']){
$retailer['under'] = $retailer['threshold'];
}
$retailer['over'] = 0;
} elseif ($search_diff > 0) {
$retailer['under'] = 0;
$retailer['over'] = $search_diff;
}
}
if (!$threshold_category || ($threshold_category == 1 && $retailer['under'] > 0) || ($threshold_category == 2 && $retailer['under'] == 0 && $retailer['over'] == 0) || ($threshold_category == 3 && $retailer['over'] > 0)){
$retailers[] = $retailer;
}
}
$pagination = $this->retailer_model->all_pages;
}
}
}
$this->load->helper('form');
//權限設定
$authority = array();
if ($this->authentic->authority('supervisor', 'purchase')){
$authority['purchase'] = true;
}
if ($this->authentic->authority('supervisor', 'info')){
$authority['info'] = true;
}
$data = [
'search' => $search,
'sales_retailer_select' => $sales_retailer_select,
'sales_dealer_select' => $sales_dealer_select,
'retailer_level_selects' => $retailer_level_selects,
'threshold_categories' => $this->threshold_categories,
'retailers' => $retailers,
'pagination' => $pagination,
'authority' => $authority,
'title' => '經銷商列表',
'view' => 'supervisor/overview',
];
$this->_preload($data);
}
public function info($retailer_id)
{
$retailer = $this->retailer_model
->with_sales_retailer()
->with_sales_dealer()
->with_role()
->with_contact_dealer()
->with_level(['with' => ['relation' => 'type']])
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料');
}
if (empty($retailer['level'])) {
$retailer['level_title'] = $retailer['role']['title'];
} else {
$retailer['level_title'] = $retailer['level']['type']['title'] . ' ' . $retailer['level']['code'];
}
$data = [
'retailer' => $retailer,
'title' => '經銷單位基本資料',
'view' => 'supervisor/info',
];
$this->_preload($data);
}
public function purchase($retailer_id, $year, $month)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料');
}
$year = (int)$year;
$month = (int)$month;
if (!$year || !$month || $month > 12){
show_error('月份錯誤');
}
$purchases = $this->purchase_model
->with_retailer()
->with_shipout_retailer()
->where('YEAR(created_at) = "' . $year . '"', null, null, false, false, true)
->where('MONTH(created_at) = "' . $month . '"', null, null, false, false, true)
->where('retailer_id', $retailer_id)
->where('isConfirmed', 1)
->get_all();
//權限設定
$authority = array();
if ($this->authentic->authority('supervisor', 'detail')){
$authority['detail'] = true;
}
$data = [
'retailer' => $retailer,
'purchases' => $purchases,
'authority' => $authority,
'title' => '經銷商進貨明細',
'view' => 'supervisor/purchase',
];
$this->_preload($data);
}
public function detail($purchase_id)
{
$purchase = $this->purchase_model
->with_transfer_from()
->with_retailer('fields:company,invoice_title')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_order_transfer(['with' =>
[
['relation' => 'order', 'with' => ['contact']],
['relation' => 'retailer'],
['relation' => 'shipout_retailer'],
]
])
->with_items(['with' =>
[
'relation' => 'product',
'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
]
])
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無進貨單資料');
}
$purchase_lib = new purchase_lib($purchase);
$purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
$purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
$purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
$shipments = [];
$allowance_payments = [];
$total_allowance_payment = 0;
if ($purchase['isShipped']) {
$real_shipin_retailer = $purchase['shipin_retailer'];
$real_shipout_retailer = $purchase['shipout_retailer'];
if (!is_null($purchase['transfer_id'])){
$transfer_to_purchase = $this->purchase_model
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->get($purchase['transfer_id']);
if ($transfer_to_purchase){
$real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
}
}
$this->load->model('payment_model');
//銷貨折讓
$payments = $this->payment_model
->with_paid_retailer('fields:company,invoice_title')
->with_received_retailer('fields:company,invoice_title')
->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
->where('pay_type', 'shipment_allowance')
->where('pay_id', $purchase_id)
->get_all();
if ($payments) {
foreach ($payments as $payment){
$payment['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
$allowance_payments[] = $payment;
if ($payment['active'] && $payment['isConfirmed']) {
$total_allowance_payment += $payment['price'];
}
}
}
$_shipments = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->order_by('id', 'asc')
->get_all();
if ($_shipments){
foreach ($_shipments as $shipment){
if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
$shipment['isReturn'] = true;
$shipment['shipout_retailer'] = $real_shipin_retailer;
$shipment['shipin_retailer'] = $real_shipout_retailer;
} else {
$shipment['shipout_retailer'] = $real_shipout_retailer;
$shipment['shipin_retailer'] = $real_shipin_retailer;
}
$shipments[] = $shipment;
if (is_null($shipment['shipment_id'])) {
$revised = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('shipment_id', $shipment['id'])
->where('isConfirmed', 0)
->order_by('id', 'asc')
->get_all();
if ($revised) {
$shipments = array_merge($shipments, $revised);
}
}
}
if ($shipments){
foreach ( array_reverse($shipments) as $shipment ) {
if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
foreach ($shipment['expirations'] as $sitem) {
foreach ($purchase['items'] as $pkey => $pitem) {
if ($sitem['product_id'] == $pitem['product_id']) {
if (!isset($purchase['items'][$pkey]['shipping_qty'])){
$purchase['items'][$pkey]['shipping_qty'] = 0;
}
if (!empty($shipment['isReturn'])){
$purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
} else {
$purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
}
}
}
}
if (empty($shipment['isReturn'])) {
break;
}
}
}
}
}
}
$data = [
'purchase' => $purchase,
'shipments' => $shipments,
'allowance_payments' => $allowance_payments,
'total_allowance_payment' => $total_allowance_payment,
'title' => '進貨單詳細資料',
'view' => 'supervisor/detail',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/layout/login.php
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="designer" content="cystudio, <EMAIL>" />
<title><?= $title ?></title>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="<KEY>"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M5LQ7CP');</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="<KEY>"
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="<KEY>" crossorigin="anonymous">
<link href="<?= base_url('css/styles.css') ?>" rel="stylesheet" type="text/css">
<style>
html, body {
background-color: #9BBB59;
}
</style>
</head>
<body>
<?php if (!empty($msg)) { ?>
<div class="container">
<div class="alert alert-info alert-dismissible">
<?= $msg ?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<?php } ?>
<?php
if (isset($data)) {
$this->load->view($view, $data);
} else {
$this->load->view($view);
}
?>
</body>
</html>
<file_sep>/application/views/guest/info.php
<div class="container">
<h1 class="mb-4 text-center">經銷商基本資料</h1>
<form method="post" id="orderForm">
<?php if (validation_errors()){ ?>
<div class="alert alert-danger">
<?=validation_errors()?>
</div>
<?php } ?>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>經銷商名稱</td>
<td colspan="3">
<input name="company" class="form-control" maxlength="20" required
value="<?= set_value('company', $guest['retailer']['company']) ?>">
</td>
</tr>
<tr>
<td>身份證字號/統一編號</td>
<td colspan="3">
<input name="identity" class="form-control" maxlength="10" required
value="<?= set_value('identity', $guest['retailer']['identity']) ?>">
</td>
</tr>
<tr>
<td>經銷商類別</td>
<td colspan="3">
<?= $guest['level']['title'] ?>
</td>
</tr>
<tr>
<td>進貨折扣</td>
<td colspan="3">
<?= $guest['level']['discount'] . '%'?>
</td>
</tr>
<tr>
<td>經銷商帳號</td>
<td colspan="3">
<input name="account" class="form-control" value="" required />
</td>
</tr>
<tr>
<td>登入密碼</td>
<td>
<input type="<PASSWORD>" name="password" class="form-control" value="" />
</td>
<td>確認密碼</td>
<td>
<input type="<PASSWORD>" name="password_confirm" class="form-control" value="" />
</td>
</tr>
<tr>
<th>輔銷人</th>
<td><?= $guest['sales_dealer']['name'] ?></td>
<th>輔銷人代號</th>
<td><?= $guest['sales_dealer']['account'] ?></td>
</tr>
<tr>
<th>輔銷單位</th>
<td colspan="3"><?= $guest['sales_retailer']['company'] ?></td>
</tr>
<tr>
<td>經銷商代表人姓名</td>
<td>
<input name="contact" class="form-control" maxlength="20" required
value="<?= set_value('contact', $guest['retailer']['contact']) ?>">
</td>
<td>性別</td>
<td>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_1" value="1"<?= set_value('gender', $guest['retailer']['gender']) == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_1">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_0" value="0"<?= set_value('gender', $guest['retailer']['gender']) === '0' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_0">女</label>
</div>
</td>
</tr>
<tr>
<td>聯絡電話1</td>
<td colspan="3">
<input name="phone" class="form-control" maxlength="20" required
value="<?= set_value('phone', $guest['retailer']['phone']) ?>">
</td>
</tr>
<tr>
<td>聯絡電話2</td>
<td colspan="3">
<input name="altPhone" class="form-control" maxlength="20"
value="<?= set_value('altPhone', $guest['retailer']['altPhone']) ?>">
</td>
</tr>
<tr>
<td>送貨地址</td>
<td colspan="3">
<input name="address" class="form-control" maxlength="100" required
value="<?= set_value('address', $guest['retailer']['address']) ?>">
</td>
</tr>
</table>
<h4 class="my-4 text-center">訂貨明細</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>項次</td>
<td>貨品編號</td>
<td>貨品名稱</td>
<td>分類</td>
<td>單價</td>
<td>訂購數量</td>
<td>金額小計</td>
<td>折扣</td>
<td>折扣價</td>
</tr>
<?php
if ($products) {
$i = 1;
foreach ($products as $pId => $product) {
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td data-th="項次" class="text-center"><?= $i ?></td>
<td data-th="貨品編號"><?= $product['p_num'] ?></td>
<td data-th="貨品名稱"><?= $product['name'] ?></td>
<td data-th="分類"><?= $product['ctName'] ?></td>
<td data-th="單價" class="text-right">$<?= number_format($product['price']) ?></td>
<td data-th="訂購數量" class="text-right"><?= number_format($product['qty']) ?></td>
<td data-th="金額小計" class="text-right">$<?= number_format($product['price'] * $product['qty']) ?></td>
<td data-th="折扣"
class="text-right"><?=$guest['level']['discount'] . '%' ?></td>
<td data-th="折扣價"
class="text-right">
$<?= number_format(floor($product['price'] * $guest['level']['discount'] / 100) * $product['qty']) ?></td>
</tr>
<?php
$i++;
}
}
?>
<tr>
<td colspan="6" class="text-right font-weight-bold">小計</td>
<td class="text-right font-weight-bold">$<?= number_format($guest['purchase']['subtotal']) ?></td>
<td class="text-right font-weight-bold">總計</td>
<td class="text-right font-weight-bold">$<?= number_format($guest['purchase']['total']) ?></td>
</tr>
<tr>
<td colspan="6" class="text-right">備註</td>
<td colspan="3">
<textarea rows="4" name="memo" class="form-control"><?= $guest['purchase']['memo'] ?></textarea>
</td>
</tr>
</table>
<div class="form-group text-center">
<input type="submit" name="cart" class="btn" value="回訂貨單" />
<input type="submit" name="checkout" class="btn btn-success" value="確認資料並下單" />
</div>
</form>
</div>
<file_sep>/application/models/Retailer_role_model.php
<?php
class Retailer_role_model extends MY_Model
{
public $table = 'olive_retailer_roles';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['retailers'] = array('Retailer_model', 'retailer_role_id', 'id');
$this->has_many['groups'] = array('Retailer_group_model', 'retailer_role_id', 'id');
$this->has_many['level_types'] = array('Retailer_level_type_model', 'retailer_role_id', 'id');
}
public function getRoleSelect()
{
$_roles = $this
->where('id', '!=', 5) //經銷商不能自行新增
->get_all();
$roles = [];
foreach ($_roles as $role){
$roles[$role['id']] = $role['title'];
}
return $roles;
}
}
?>
<file_sep>/application/models/Shipment_model.php
<?php
class Shipment_model extends MY_Model
{
public $table = 'olive_shipments';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
$this->has_one['shipin_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipin_retailer_id');
$this->has_many['items'] = array('Shipment_item_model', 'shipment_id', 'id');
$this->has_many['expirations'] = array('Shipment_expiration_model', 'shipment_id', 'id');
$this->has_one['revise'] = array('foreign_model' => 'Shipment_revise_model', 'foreign_table' => 'olive_shipment_revises', 'foreign_key' => 'shipment_id', 'local_key' => 'id');
$this->has_one['confirm'] = array('foreign_model' => 'Confirm_model', 'foreign_table' => 'olive_confirms', 'foreign_key' => 'confirm_id', 'local_key' => 'id');
$this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'ship_id');
}
public function generateShipmentConfirmLabel($shipment, $showMemo = false)
{
$string = '';
if (is_null($shipment['isConfirmed'])){
$string .= '<span class="badge badge-warning">待確認</span>';
} else {
$confirm = $shipment['confirm'];
if ($confirm) {
$this->load->helper('data_format');
$string .= confirmStatus($confirm['audit'], $confirm['memo']);
if ($showMemo) {
$string .= '<div>' . $confirm['memo'] . '</div>';
}
}
}
return $string;
}
}
?>
<file_sep>/application/views/income/overview.php
<div class="container">
<h1 class="mb-4">營業資訊</h1>
<form id="search_form">
<div class="card mb-4">
<div class="card-header">搜尋</div>
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-3">
<label for="purchaseNum">單位</label>
<select name="retailer_id" class="form-control" required>
<option>本單位</option>
<?php foreach ($retailers as $retailer){ ?>
<option value="<?=$retailer['retailer_id']?>"<?php if ($search['retailer_id'] == $retailer['retailer_id']){ echo 'selected'; } ?>><?=$retailer['retailer']['company']?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="created_start">查詢日期起</label>
<input type="date" class="form-control" name="created_start" required value="<?=$search['created_start']?>" />
</div>
<div class="form-group col-md-3">
<label for="created_end">查詢日期訖</label>
<input type="date" class="form-control" name="created_end" required value="<?=$search['created_end']?>" />
</div>
</div>
</div>
<div class="card-footer text-center">
<input type="submit" value="搜尋" class="btn btn-primary" />
<a href="<?=base_url('/income/overview')?>" class="btn btn-light">重設</a>
</div>
</div>
</form>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">分錄</th>
<th class="text-center">金額</th>
</tr>
<?php
if ($income) {
if ($income['revenue']){
foreach ($income['revenue'] as $revenue) {
?>
<tr>
<th class="text-left"><?= $revenue['name'] ?></th>
<td class="text-right">$ <?= number_format($revenue['total']) ?></td>
</tr>
<?php
}
}
if ($income['expense']){
foreach ($income['expense'] as $expense) {
?>
<tr>
<th class="text-left"><?= $expense['name'] ?></th>
<td class="text-right">$ -<?= number_format($expense['total']) ?></td>
</tr>
<?php
}
}
?>
<tr class="bg-light">
<th class="text-left">毛利</th>
<th class="text-right">$ <?= number_format($income['total']) ?></th>
</tr>
<?php
} else {
?>
<tr>
<td colspan="2" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
</div><file_sep>/application/models/Retailer_model.php
<?php
class Retailer_model extends MY_Model
{
public $table = 'olive_retailers';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['dealers'] = array('Dealer_model', 'retailer_id', 'id');
$this->has_one['contact_dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'contact_dealer_id');
$this->has_one['level'] = array('foreign_model' => 'Retailer_level_model', 'foreign_table' => 'olive_retailer_levels', 'foreign_key' => 'id', 'local_key' => 'retailer_level_id');
$this->has_one['role'] = array('foreign_model' => 'Retailer_role_model', 'foreign_table' => 'olive_retailer_roles', 'foreign_key' => 'id', 'local_key' => 'retailer_role_id');
$this->has_many['relationships'] = array('Retailer_relationship_model', 'retailer_id', 'id');
$this->has_one['sales_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'sales_retailer_id');
$this->has_one['sales_dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'sales_dealer_id');
}
public function getRetailerSelect()
{
$_retailers = $this->get_all();
$retailers = [];
foreach ($_retailers as $retailer){
$retailers[$retailer['id']] = $retailer['company'];
}
return $retailers;
}
public function getRetailerHasStock()
{
return $this
->where('hasStock', 1)
->where('totalStock', 1)
->order_by('retailer_role_id', 'asc')
->get_all();
}
}
?>
<file_sep>/application/migrations/040_update_shipment.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_shipment extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_shipments', [
'product_verify' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
'after' => 'memo',
],
'fare_verify' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
'after' => 'product_verify',
],
'shipment_verify' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
'after' => 'fare_verify',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_shipments', 'product_verify');
$this->dbforge->drop_column('olive_shipments', 'fare_verify');
$this->dbforge->drop_column('olive_shipments', 'shipment_verify');
}
}<file_sep>/application/models/Payment_model.php
<?php
class Payment_model extends MY_Model
{
public $table = 'olive_payments';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['paid_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'paid_retailer_id');
$this->has_one['received_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'received_retailer_id');
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'pay_id');
$this->has_one['confirm'] = array('foreign_model' => 'Confirm_model', 'foreign_table' => 'olive_confirms', 'foreign_key' => 'confirm_id', 'local_key' => 'id');
}
public function generatePaymentConfirmLabel($payment, $showMemo = false)
{
$string = '';
if (is_null($payment['isConfirmed'])){
$string .= '<span class="badge badge-warning">待確認</span>';
} else {
$confirm = $payment['confirm'];
if ($confirm) {
$string .= confirmStatus($confirm['audit'], $confirm['memo'], '確認已收款');
if ($showMemo) {
$string .= '<div>' . $confirm['memo'] . '</div>';
}
}
}
return $string;
}
}
?>
<file_sep>/application/views/capital/relationship/invoice/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">編輯<?= $relationship['retailer']['company'] ?> 發票關係單位</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">出貨單位</label>
<input class="form-control-plaintext" value="<?= $relationship['relation']['company'] ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">發票單位</label>
<input class="form-control-plaintext" value="<?= $relationship['alter']['company'] ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">折扣</label>
<div class="input-group">
<input type="number" name="discount" class="form-control text-right" max="100" min="1" value="<?= set_value('discount', $relationship['discount']) ?>"/>
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_relationship_invoice/overview/' . $relationship['retailer_id'])?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/controllers/Capital_customer_level.php
<?php
class Capital_customer_level extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('customer_level_model');
$this->session->set_userdata('return_page', base_url('/capital_customer_level/overview'));
}
public function overview()
{
$levels = $this->customer_level_model
->with_type()
->get_all();
//權限設定
$authority = array();
if ($this->authentic->authority('capital_customer_level', 'edit')){
$authority['edit'] = true;
}
$data = [
'levels' => $levels,
'authority' => $authority,
'title' => '會員資格管理',
'view' => 'capital/customer_level/overview',
];
$this->_preload($data);
}
public function edit($customer_level_id)
{
$level = $this->customer_level_model
->with_type()
->get($customer_level_id);
if (!$customer_level_id || !$level) {
show_error('查無會員資格資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');
$this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
if ($this->form_validation->run() !== FALSE) {
$update_data = [
'title' => $this->input->post('title'),
'discount' => $this->input->post('discount'),
'description' => $this->input->post('description'),
];
$this->customer_level_model->update($update_data, ['id' => $customer_level_id]);
redirect(base_url('/capital_customer_level/overview/'));
}
}
$data = [
'level' => $level,
'title' => '編輯會員資格管理',
'view' => 'capital/customer_level/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/controllers/Seeder.php
<?php
class Seeder extends CI_Controller
{
public function __construct()
{
parent::__construct();
if (!$this->input->is_cli_request()) {
show_error('你沒有權限使用');
}
}
public function all()
{
$this->retailer_role();
$this->retailer_level_type();
$this->retailer_level();
$this->retailer_group();
$this->retailer();
$this->retailer_relationship();
$this->privilege();
$this->customer_level();
$this->db->truncate('olive_commissions');
$this->db->truncate('olive_combos');
$this->db->truncate('olive_combo_items');
$this->db->truncate('olive_confirms');
$this->db->truncate('olive_coupons');
$this->db->truncate('olive_coupon_approves');
$this->db->truncate('olive_customers');
$this->db->truncate('olive_customer_level_histories');
$this->db->truncate('olive_expenses');
$this->db->truncate('olive_free_package_items');
$this->db->truncate('olive_old_customers');
$this->db->truncate('olive_orders');
$this->db->truncate('olive_order_contacts');
$this->db->truncate('olive_order_items');
$this->db->truncate('olive_order_returns');
$this->db->truncate('olive_order_recipients');
$this->db->truncate('olive_payments');
$this->db->truncate('olive_purchases');
$this->db->truncate('olive_promotes');
$this->db->truncate('olive_promote_items');
$this->db->truncate('olive_purchase_items');
$this->db->truncate('olive_recommends');
$this->db->truncate('olive_recommend_templates');
$this->db->truncate('olive_shipments');
$this->db->truncate('olive_shipment_items');
$this->db->truncate('olive_stocks');
$this->db->truncate('olive_stock_countings');
$this->db->truncate('olive_stock_counting_items');
echo 'Seeder 成功';
}
public function retailer_role()
{
$this->db->truncate('olive_retailer_roles');
$this->load->model('retailer_role_model');
$roles = [
[
'title' => '總代理',
'account_prefix' => 'ZZ',
],
[
'title' => '總經銷',
'account_prefix' => 'XX',
],
[
'title' => '皮瑪斯門市',
'account_prefix' => 'YY',
],
[
'title' => '總代理門市與總代理百貨專櫃',
'account_prefix' => 'SS',
],
[
'title' => '經銷商',
],
];
foreach ($roles as $role) {
$this->retailer_role_model->insert($role);
}
}
public function retailer_level_type()
{
$this->db->truncate('olive_retailer_level_types');
$this->load->model('retailer_level_type_model');
$roles = [
[
'retailer_role_id' => 5,
'type' => 'A',
'title' => '個人經銷商',
'description' => '<table class="table table-bordered"> <tbody> <tr> <td> </td> <td>經銷商類別</td> <td>代碼</td> <td>進貨折數</td> <td>首次進貨門檻</td> <td>每月進貨門檻</td> <td>裝修費(櫃體&形象)</td> <td>保證金</td> <td>輔銷人輔導金(經銷商)</td> <td>輔銷人輔導金(總經銷人員或股東)</td> <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td> </tr> <tr> <td rowspan="3">個人經銷商</td> <td>經銷人A</td> <td>AA</td> <td>定價80%</td> <td>2萬</td> <td>0.5萬/月</td> <td rowspan="3">-</td> <td rowspan="3">0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <td>經銷人B</td> <td>AB</td> <td>定價60%</td> <td>35萬</td> <td>3萬/月</td> <td>3%</td> <td>3%</td> <td>3%</td> </tr> <tr> <td>經銷人C</td> <td>AC</td> <td>定價60%</td> <td>20萬</td> <td>5萬/月</td> <td>3%</td> <td>3%</td> <td>3%</td> </tr> </tbody></table>',
],
[
'retailer_role_id' => 5,
'type' => 'B',
'title' => '櫃位經銷商',
'description' => '<table class="table table-bordered"> <tbody> <tr> <td> </td> <td>經銷商類別</td> <td>代碼</td> <td>進貨折數</td> <td>首次進貨門檻</td> <td>每月進貨門檻</td> <td>裝修費(櫃體&形象)</td> <td>保證金</td> <td>輔銷人輔導金(經銷商)</td> <td>輔銷人輔導金(總經銷人員或股東)</td> <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td> </tr> <tr> <td rowspan="3">櫃位經銷商</td> <td>經銷櫃位A</td> <td>BA</td> <td>定價60%</td> <td>35萬</td> <td>3萬/月</td> <td rowspan="3">每一櫃子 5-8 萬/小招 3-5 萬<br> /直招及帆布各 4–8 萬<br> /輸出 5-10 萬<br> /教育訓練費 3 萬<br> (若參與皮革護理業務再加 5 萬)<br> /飾品 1 萬/裝修費工料另訂</td> <td rowspan="3">5萬</td> <td>3%</td> <td>3%</td> <td>3%</td> </tr> <tr> <td>經銷櫃位B</td> <td>BB</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷櫃位C</td> <td>BC</td> <td>定價47%</td> <td>90萬</td> <td>10萬/月</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> </tbody></table>',
],
[
'retailer_role_id' => 5,
'type' => 'C',
'title' => '店面經銷商',
'description' => '<table class="table table-bordered"> <tbody> <tr> <td> </td> <td>經銷商類別</td> <td>代碼</td> <td>進貨折數</td> <td>首次進貨門檻</td> <td>每月進貨門檻</td> <td>裝修費(櫃體&形象)</td> <td>保證金</td> <td>輔銷人輔導金(經銷商)</td> <td>輔銷人輔導金(總經銷人員或股東)</td> <td>輔銷人輔導金(皮瑪斯門市人員或股東)</td> </tr> <tr> <td rowspan="4">店面經銷商:<br/>經銷店面之特定資訊於整體宣傳上之媒介: 名片 店卡 型錄 提袋 官網 臉書 IG 免費服務專線</td> <td>經銷店面A</td> <td>CA</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>160萬(室內12坪內)</td> <td rowspan="4">5萬</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷店面B</td> <td>CB</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>190萬(室內12-20坪內)</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷店面C</td> <td>CC</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>220萬(室內20-35坪內)</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> <tr> <td>經銷店面D</td> <td>CD</td> <td>定價55%</td> <td>55萬</td> <td>10萬/月</td> <td>250萬(室內35-50坪內)</td> <td>2%</td> <td>2%</td> <td>2%</td> </tr> </tbody></table>',
],
];
foreach ($roles as $role) {
$this->retailer_level_type_model->insert($role);
}
}
public function retailer_level()
{
$this->db->truncate('olive_retailer_levels');
$this->load->model('retailer_level_model');
$levels = [
[
'discount' => 80,
'retailer_level_type_id' => 1,
'code' => 'A',
'firstThreshold' => '20000',
'monthThreshold' => '5000',
],
[
'discount' => 60,
'retailer_level_type_id' => 1,
'code' => 'B',
'firstThreshold' => '350000',
'monthThreshold' => '30000',
],
[
'discount' => 60,
'retailer_level_type_id' => 1,
'code' => 'C',
'firstThreshold' => '200000',
'monthThreshold' => '50000',
],
[
'discount' => 60,
'retailer_level_type_id' => 2,
'code' => 'A',
'firstThreshold' => '350000',
'monthThreshold' => '30000',
],
[
'discount' => 55,
'retailer_level_type_id' => 2,
'code' => 'B',
'firstThreshold' => '550000',
'monthThreshold' => '100000',
],
[
'discount' => 47,
'retailer_level_type_id' => 2,
'code' => 'C',
'firstThreshold' => '900000',
'monthThreshold' => '100000',
],
[
'discount' => 55,
'retailer_level_type_id' => 3,
'code' => 'A',
'firstThreshold' => '550000',
'monthThreshold' => '100000',
],
[
'discount' => 55,
'retailer_level_type_id' => 3,
'code' => 'B',
'firstThreshold' => '550000',
'monthThreshold' => '100000',
],
[
'discount' => 55,
'retailer_level_type_id' => 3,
'code' => 'C',
'firstThreshold' => '550000',
'monthThreshold' => '100000',
],
[
'discount' => 55,
'retailer_level_type_id' => 3,
'code' => 'D',
'firstThreshold' => '550000',
'monthThreshold' => '100000',
],
];
foreach ($levels as $level) {
$this->retailer_level_model->insert($level);
}
}
public function retailer_group()
{
$this->db->truncate('olive_retailer_groups');
$this->load->model('retailer_group_model');
$levels = [
[
'retailer_role_id' => 1, //總代理
'retailer_level_type_id' => null,
'title' => '徐總',
],
[
'retailer_role_id' => 1,
'retailer_level_type_id' => null,
'title' => '秘書長',
],
[
'retailer_role_id' => 1,
'retailer_level_type_id' => null,
'title' => '品牌設計',
],
[
'retailer_role_id' => 2, //總經銷 4
'retailer_level_type_id' => null,
'title' => '總監',
],
[
'retailer_role_id' => 2,
'retailer_level_type_id' => null,
'title' => '董事',
],
[
'retailer_role_id' => 2,
'retailer_level_type_id' => null,
'title' => '行政主任',
],
[
'retailer_role_id' => 3, //門市 7
'retailer_level_type_id' => null,
'title' => '股東',
],
[
'retailer_role_id' => 3,
'retailer_level_type_id' => null,
'title' => '店長',
],
[
'retailer_role_id' => 3,
'retailer_level_type_id' => null,
'title' => '副店長',
],
[
'retailer_role_id' => 3,
'retailer_level_type_id' => null,
'title' => '營業員',
],
[
'retailer_role_id' => 4, //百貨 11
'retailer_level_type_id' => null,
'title' => '店長',
],
[
'retailer_role_id' => 4,
'retailer_level_type_id' => null,
'title' => '副店長',
],
[
'retailer_role_id' => 4,
'retailer_level_type_id' => null,
'title' => '營業員',
],
[
'retailer_role_id' => 5, //個人經銷商 14
'retailer_level_type_id' => 1,
'title' => '個人經銷商',
],
[
'retailer_role_id' => 5, //櫃位經銷商 15
'retailer_level_type_id' => 2,
'title' => '負責人',
],
[
'retailer_role_id' => 5,
'retailer_level_type_id' => 2,
'title' => '營業員',
],
[
'retailer_role_id' => 5, //店面經銷商 17
'retailer_level_type_id' => 3,
'title' => '店東',
],
[
'retailer_role_id' => 5,
'retailer_level_type_id' => 3,
'title' => '店長',
],
[
'retailer_role_id' => 5,
'retailer_level_type_id' => 3,
'title' => '副店長',
],
[
'retailer_role_id' => 5,
'retailer_level_type_id' => 3,
'title' => '營業員',
],
];
foreach ($levels as $level) {
$this->retailer_group_model->insert($level);
}
}
public function retailer()
{
$this->db->truncate('olive_dealers');
$this->db->truncate('olive_retailers');
//seeder default 總經銷
$this->load->model('dealer_model');
$this->load->model('retailer_model');
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 1,
'serialNum' => '00001',
'companyNum' => 'ZZ00001',
'company' => '總代理',
'eta_days' => 60,
'hasStock' => 1,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 1,
'account' => 'ZZ00001',
'password' => $this->authentic->_mix('password'),
'name' => '徐總',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 2,
'serialNum' => '00001',
'companyNum' => 'XX00001',
'company' => '華利國際有限公司',
'invoice_title' => '華利國際有限公司',
'address' => '台中市西屯區台灣大道二段812號二樓',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'totalStock' => 1,
'eta_days' => 15,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 4,
'account' => 'YY00001',
'password' => $this->authentic->_mix('password'),
'name' => '總監',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 4,
'account' => 'mark',
'password' => $this->authentic->_mix('<PASSWORD>'),
'name' => 'Mark',
'isLocked' => 1,
]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 3,
'serialNum' => '00002',
'companyNum' => 'XX00002',
'company' => '皮瑪斯台北忠孝門市',
'invoice_title' => '實現潔淨保養名鋪',
'address' => '台北市忠孝東路四段101巷25號',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'totalStock' => 1,
'eta_days' => 15,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 8,
'account' => 'YY00002',
'password' => $this->authentic->_mix('password'),
'name' => '皮瑪斯台北店長',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 3,
'serialNum' => '00003',
'companyNum' => 'XX00003',
'company' => '皮瑪斯新竹西大門市',
'invoice_title' => '永遠潔淨保養名鋪',
'address' => '新竹市東區西大路107號一樓',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'totalStock' => 1,
'eta_days' => 15,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 8,
'account' => 'YY00003',
'password' => $this->authentic->_mix('password'),
'name' => '皮瑪斯新竹店長',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 3,
'serialNum' => '00004',
'companyNum' => 'XX00004',
'company' => '皮瑪斯台中台灣大道門市',
'invoice_title' => '堅定潔淨保養名鋪',
'address' => '台中市台灣大道二段812號一樓',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'totalStock' => 1,
'eta_days' => 15,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 8,
'account' => 'YY00004',
'password' => $this->authentic->_mix('password'),
'name' => '皮瑪斯台中店長',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 3,
'serialNum' => '00005',
'companyNum' => 'XX00005',
'company' => '皮瑪斯台南永華門市',
'invoice_title' => '繁榮潔淨保養名鋪',
'address' => '台南市中西區永華路一段72號一樓',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'totalStock' => 1,
'eta_days' => 15,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 8,
'account' => 'YY00005',
'password' => $this->authentic->_mix('<PASSWORD>'),
'name' => '皮瑪斯台南店長',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 3,
'serialNum' => '00006',
'companyNum' => 'XX00006',
'company' => '皮瑪斯高雄中華五福門市',
'invoice_title' => '幸福潔淨保養名鋪',
'address' => '高雄市前金區中華四路351號一樓',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'totalStock' => 1,
'eta_days' => 15,
'isLocked' => 1,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 8,
'account' => 'YY00006',
'password' => $this->authentic->_mix('password'),
'name' => '皮瑪斯高雄店長',
'isLocked' => 1,
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 4,
'serialNum' => '00001',
'companyNum' => 'SS00001',
'company' => '新北淡水門市',
'invoice_title' => '新北淡水門市',
'address' => ' 新北市中正路72-1號',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'eta_days' => 15,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 11,
'account' => 'SS00001',
'password' => $this->authentic->_mix('password'),
'name' => '新北淡水門市店長',
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 4,
'serialNum' => '00002',
'companyNum' => 'SS00002',
'company' => '台北大葉高島屋專櫃',
'invoice_title' => '台北大葉高島屋專櫃',
'address' => ' 台北市忠誠路2段55號大葉高島屋1F',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'eta_days' => 15,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 11,
'account' => 'SS00002',
'password' => $this->authentic->_mix('password'),
'name' => '台北大葉高島屋專櫃店長',
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 4,
'serialNum' => '00003',
'companyNum' => 'SS00003',
'company' => '新竹巨城百貨專櫃',
'invoice_title' => '新竹巨城百貨專櫃',
'address' => '新竹市中央路229號巨城百貨3F',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'eta_days' => 15,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 11,
'account' => 'SS00003',
'password' => $this->authentic->_mix('password'),
'name' => '新竹巨城百貨專櫃店長',
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$retailer_id = $this->retailer_model->insert([
'retailer_role_id' => 4,
'serialNum' => '00004',
'companyNum' => 'SS00004',
'company' => '臺中金典綠園道專櫃',
'invoice_title' => '臺中金典綠園道專櫃',
'address' => '台中市健行路1049號金典綠園道1F',
'purchaseThreshold' => 10000,
'hasStock' => 1,
'eta_days' => 15,
]);
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => 11,
'account' => 'SS00004',
'password' => $this->authentic->_mix('<PASSWORD>'),
'name' => '臺中金典綠園道專櫃店長',
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
}
public function retailer_relationship()
{
$this->db->truncate('olive_retailer_relationships');
$this->load->model('retailer_relationship_model');
$relationships = [
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 8,
// 'relation_retailer_id' => 1,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 9,
// 'relation_retailer_id' => 1,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 10,
// 'relation_retailer_id' => 1,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 11,
// 'relation_retailer_id' => 1,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 3,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 4,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 5,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 6,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 7,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 8,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 9,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 10,
// 'relation_retailer_id' => 2,
// ],
// [
// 'relation_type' => 'supervisor',
// 'retailer_id' => 11,
// 'relation_retailer_id' => 2,
// ],
[
'relation_type' => 'shipout',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'discount' => 45,
],
[
'relation_type' => 'shipout',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 3,
'relation_retailer_id' => 2,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 4,
'relation_retailer_id' => 2,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 5,
'relation_retailer_id' => 2,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 6,
'relation_retailer_id' => 2,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 7,
'relation_retailer_id' => 2,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 8,
'relation_retailer_id' => 1,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 9,
'relation_retailer_id' => 1,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 10,
'relation_retailer_id' => 1,
'discount' => 55,
],
[
'relation_type' => 'shipout',
'retailer_id' => 11,
'relation_retailer_id' => 1,
'discount' => 55,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'shipin',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'shipin',
'retailer_id' => 3,
'relation_retailer_id' => 2,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'shipin',
'retailer_id' => 4,
'relation_retailer_id' => 2,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'shipin',
'retailer_id' => 5,
'relation_retailer_id' => 2,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'shipin',
'retailer_id' => 6,
'relation_retailer_id' => 2,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'shipin',
'retailer_id' => 7,
'relation_retailer_id' => 2,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'shipin',
'retailer_id' => 8,
'relation_retailer_id' => 1,
'alter_retailer_id' => 8,
],
[
'relation_type' => 'shipin',
'retailer_id' => 9,
'relation_retailer_id' => 1,
'alter_retailer_id' => 9,
],
[
'relation_type' => 'shipin',
'retailer_id' => 10,
'relation_retailer_id' => 1,
'alter_retailer_id' => 10,
],
[
'relation_type' => 'shipin',
'retailer_id' => 11,
'relation_retailer_id' => 1,
'alter_retailer_id' => 11,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 3,
'discount' => 42,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 3,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 4,
'discount' => 42,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 4,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 5,
'discount' => 42,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 5,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 6,
'discount' => 42,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 6,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 1,
'alter_retailer_id' => 7,
'discount' => 42,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 2,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'invoice',
'retailer_id' => 2,
'relation_retailer_id' => 7,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 2,
'relation_retailer_id' => 2,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 2,
'relation_retailer_id' => 3,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 2,
'relation_retailer_id' => 4,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 2,
'relation_retailer_id' => 5,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 2,
'relation_retailer_id' => 6,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 2,
'relation_retailer_id' => 7,
],
[
'relation_type' => 'invoice',
'retailer_id' => 3,
'relation_retailer_id' => 2,
'alter_retailer_id' => 3,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 3,
'relation_retailer_id' => 3,
],
[
'relation_type' => 'invoice',
'retailer_id' => 4,
'relation_retailer_id' => 2,
'alter_retailer_id' => 4,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 4,
'relation_retailer_id' => 4,
],
[
'relation_type' => 'invoice',
'retailer_id' => 5,
'relation_retailer_id' => 2,
'alter_retailer_id' => 5,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 5,
'relation_retailer_id' => 5,
],
[
'relation_type' => 'invoice',
'retailer_id' => 6,
'relation_retailer_id' => 2,
'alter_retailer_id' => 6,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 6,
'relation_retailer_id' => 6,
],
[
'relation_type' => 'invoice',
'retailer_id' => 7,
'relation_retailer_id' => 2,
'alter_retailer_id' => 7,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 7,
'relation_retailer_id' => 7,
],
[
'relation_type' => 'invoice',
'retailer_id' => 8,
'relation_retailer_id' => 1,
'alter_retailer_id' => 8,
],
[
'relation_type' => 'invoice',
'retailer_id' => 9,
'relation_retailer_id' => 1,
'alter_retailer_id' => 9,
],
[
'relation_type' => 'invoice',
'retailer_id' => 10,
'relation_retailer_id' => 1,
'alter_retailer_id' => 10,
],
[
'relation_type' => 'invoice',
'retailer_id' => 11,
'relation_retailer_id' => 1,
'alter_retailer_id' => 11,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 8,
'relation_retailer_id' => 8,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 9,
'relation_retailer_id' => 9,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 10,
'relation_retailer_id' => 10,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => 11,
'relation_retailer_id' => 11,
],
];
foreach ($relationships as $relationship) {
$this->retailer_relationship_model->insert($relationship);
}
}
public function privilege()
{
$this->db->truncate('olive_privileges');
$this->load->model('privilege_model');
$privileges = [
[
'classname' => 'capital_dealer',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_dealer',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_dealer',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_dealer',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_level',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_level',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_level',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_level_type',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_level_type',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_customer_level',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_customer_level',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_privilege',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_privilege',
'methodname' => 'apps',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_privilege',
'methodname' => 'authority',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_relationship_invoice',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_relationship_invoice',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_relationship_invoice_send',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_relationship_shipin',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_relationship_shipout',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_relationship_shipout',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer_group',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer_group',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer_group',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_retailer_role',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_combo',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_combo',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_combo',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_combo',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_combo',
'methodname' => 'check_total',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_free_package',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_free_package',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_free_package',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_free_package',
'methodname' => 'check_duplicate',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_promote',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_promote',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_promote',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_promote',
'methodname' => 'advance',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_promote',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'capital_stock',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'stock',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock',
'methodname' => 'edit',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 0, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'index',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'detail',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'set_print',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'process_print',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'add',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'stock_counting',
'methodname' => 'edit',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'guest',
'methodname' => 'cart',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'guest',
'methodname' => 'check_total',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'guest',
'methodname' => 'adminCheck',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'guest',
'methodname' => 'check_authentic',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'guest',
'methodname' => 'info',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'detail',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'detail2',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 0, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'check_total',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'import_edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'import_confirm_supple',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'import_confirm_refund',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'purchase',
'methodname' => 'import_return',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'transfer',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'detail',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'detail2',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 0, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'confirm',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'export_response',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'export_method_supple',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'export_method_refund',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'transfer',
'methodname' => 'export_return_confirm',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'payment',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'payment',
'methodname' => 'purchase',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'payment',
'methodname' => 'add',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'payment',
'methodname' => 'confirms',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'payment',
'methodname' => 'confirm',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'payment',
'methodname' => 'cancel',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'shipment',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'shipment',
'methodname' => 'detail',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'shipment',
'methodname' => 'add',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'shipment',
'methodname' => 'confirm',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'shipment',
'methodname' => 'check_qty',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'shipment',
'methodname' => 'cancel',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'commission',
'methodname' => 'dealers',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'commission',
'methodname' => 'dealer',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 0, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'confirm',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'income',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'income',
'methodname' => 'product',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'consumer',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'upgrade',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'old',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'old_detail',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'conv_old',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'active_old',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'customer',
'methodname' => 'import',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'index',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'detail',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'check_qty',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'check_coupon',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'cancel',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'old',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'check_oldphone',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'trashed',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'recover',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'payAtShipped',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'shipping',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'paying',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'reject',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'consumer',
'methodname' => 'orderReturn',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'coupon',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'coupon',
'methodname' => 'detail',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'coupon',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'coupon',
'methodname' => 'confirm',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'coupon',
'methodname' => 'approved',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 0, //門市店長
11 => 0, //百貨店長
14 => 0, //個人經銷商
15 => 0, //櫃位經銷商負責人
17 => 0, //店面經銷商店東
]),
],
[
'classname' => 'recommend',
'methodname' => 'overview',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend',
'methodname' => 'temp',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend',
'methodname' => 'add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend',
'methodname' => 'print_recommend',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend',
'methodname' => 'edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'index',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'confirm',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'confirm_edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'inside',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'inside_add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'inside_edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'outside',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'outside_add',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'outside_edit',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'recommend_template',
'methodname' => 'confirming',
'rules' => serialize([
1 => 0, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'dealer',
'methodname' => 'edit',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'dealer',
'methodname' => 'profile',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'dealer',
'methodname' => 'password',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'dealer',
'methodname' => 'check_password',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'retailer',
'methodname' => 'overview',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 0, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'retailer',
'methodname' => 'add',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'retailer',
'methodname' => 'edit',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
[
'classname' => 'retailer',
'methodname' => 'cancel',
'rules' => serialize([
1 => 1, //總代理徐總
4 => 1, //總經銷總監
8 => 1, //門市店長
11 => 1, //百貨店長
14 => 1, //個人經銷商
15 => 1, //櫃位經銷商負責人
17 => 1, //店面經銷商店東
]),
],
];
foreach ($privileges as $privilege) {
$this->privilege_model->insert($privilege);
}
}
public function customer_level()
{
$this->db->truncate('olive_customer_levels');
//seeder default
$this->load->model('customer_level_model');
$levels = [
[
'discount' => 95,
'title' => '飄雪白卡',
'description' => '<p>會員福利:</p>
<p>消費享9.5折優惠。</p>
<p>資格取得:</p>
<p>一顆橄欖相關商品一次消費滿12,000元、或年度消費滿20,000元、或皮瑪斯會員,可申請飄雪白卡會員。</p>
<p>「年度」:每年8月1日至次年7月31日為一年度。</p>
',
],
[
'discount' => 90,
'title' => '春水綠卡',
'description' => '<p>會員福利:</p>
<p>消費享9折優惠。</p>
<p>資格取得:</p>
<p>白卡會員年度消費次數達6次以上即可自動升等為綠卡會員。</p>
<p>「年度」:每年8月1日至次年7月31日為一年度。</p>
',
],
[
'discount' => 88,
'title' => '曜石黑卡',
'description' => '<p>會員福利:</p>
<p>1.一顆橄欖全系列商品享定價8.8折優惠。</p>
<p>2.免費使用一顆橄欖新品發表試用品。</p>
<p>3.免費參加年度感恩餐會。</p>
<p>4.享年度南法普羅旺斯免費住宿3天2夜(含莊園體驗及2食2泊招待,不含機票及交通)。</p>
<p>資格取得:</p>
<p>年度消費次數達20次以上、且消費金額滿330,000元之綠卡會員,自動升級為黑卡會員。</p>
<p>「年度」:每年8月1日至次年7月31日為一年度。</p>
',
],
];
foreach ($levels as $level) {
$this->customer_level_model->insert($level);
}
}
public function shipment_items_convert()
{
$this->load->model('shipment_model');
$this->load->model('shipment_expiration_model');
$shipments = $this->shipment_model
->with_items()
->get_all();
if ($shipments){
foreach ($shipments as $shipment){
$products = [];
if (!empty($shipment['items'])) {
foreach ($shipment['items'] as $item) {
if (!isset($products[$item['product_id']])) {
$products[$item['product_id']] = 0;
}
$products[$item['product_id']] += $item['qty'];
}
foreach ($products as $product_id => $q) {
$this->shipment_expiration_model->insert([
'shipment_id' => $shipment['id'],
'product_id' => $product_id,
'expired_at' => null,
'qty' => $q,
]);
}
}
}
}
}
}
?><file_sep>/application/views/stock_counting/index.php
<div class="container">
<div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
<?php if (!empty($authority['print'])){ ?>
<a href="<?=base_url('/stock_counting/set_print')?>" class="btn btn-success mr-4">「盤點清冊」下載</a>
<?php } ?>
<?php if (!empty($authority['add'])){ ?>
<a href="<?=base_url('/stock_counting/add')?>" class="btn btn-success mr-4">盤盈虧報表新增</a>
<?php } ?>
<?php if (!empty($authority['overview'])){ ?>
<a href="<?=base_url('/stock_counting/overview')?>" class="btn btn-success">盤點歷史紀錄列表</a>
<?php } ?>
</div>
</div><file_sep>/application/views/consumer/add.php
<div class="container">
<?php
if (!$customer && !validation_errors()) {
?>
<div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
<a href="#" class="btn btn-success mr-4" id="btn-firstTime" >消費者首次訂購</a>
<a href="<?=base_url('/customer/overview')?>" class="btn btn-success">消費者非首次訂購</a>
</div>
<?php } ?>
<div id="order_wrap" class="<?php if (!$customer && !validation_errors()) { echo 'd-none'; }?>">
<h1 class="mb-4 text-center"><?=$headline?></h1>
<form method="post" id="orderForm">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="row justify-content-md-center">
<div class="col-md-8">
<?php if ($isOld){ ?>
<div class="form-group">
<label class="font-weight-bold">舊有會員轉換說明</label>
<ul>
<li>舊有會員召回完成實名登記者即成為綠卡會員。</li>
<li>舊有會員一年消費未滿 12次或未單次購買12,000元於 實名登記完隔年降為飄雪白卡。</li>
<li>舊有會員達2年未消費,自動喪失會員資格。</li>
</ul>
</div>
<?php } ?>
<div id="customer_info">
<div class="form-group">
<label class="font-weight-bold">姓名*</label>
<input name="name" class="form-control"
value="<?= set_value('name', isset($customer['name']) ? $customer['name'] : '') ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">電話*</label>
<input name="phone" class="form-control"
value="<?= set_value('phone', isset($customer['phone']) ? $customer['phone'] : '') ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">聯絡地址*</label>
<input name="address" class="form-control"
value="<?= set_value('address', isset($customer['address']) ? $customer['address'] : '') ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">收貨地址</label>
<input name="altAddress" class="form-control" value="<?= set_value('altAddress') ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">性別</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_1"
value="1"<?= set_value('gender', isset($customer['gender']) ? $customer['gender'] : '') == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_1">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_0"
value="0"<?= set_value('gender', isset($customer['gender']) ? $customer['gender'] : '') === '0' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_0">女</label>
</div>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">生日</label>
<div class="form-row">
<div class="col">
<select class="form-control" name="birthday_year">
<option value="">生日年</option>
<?php for ($i = date('Y'); $i > date('Y', strtotime('-100 years')); $i--){ ?>
<option value="<?=$i?>"<?php if (set_value('birthday_year', isset($customer['birthday_year']) ? $customer['birthday_year'] : '') == $i){ echo ' selected'; } ?>><?=$i?></option>
<?php } ?>
</select>
</div>
<div class="col">
<input id="birthday" name="birthday" class="form-control" value="<?= set_value('birthday', isset($customer['birthday']) ? date('m/d', strtotime($customer['birthday'])) : '') ?>"/>
</div>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">Email</label>
<input type="email" name="email" class="form-control"
value="<?= set_value('email', isset($customer['email']) ? $customer['email'] : '') ?>"/>
</div>
<?php if (!$isOld && isset($customer['id'])) { ?>
<div class="form-group">
<a target="_blank" href="<?= base_url('/customer/consumer/' . $customer['id']) ?>"
class="btn btn-info btn-sm"><i class="fas fa-search"></i> 歷史消費記錄</a>
</div>
<?php } ?>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="isDealer" name="isDealer" value="1"<?php if (set_value('isDealer', (empty($customer['isDealer']) ? 0 : 1) == 1)){ echo 'checked';}?>>
<label class="form-check-label" for="isDealer">該顧客為本公司員工</label>
</div>
<div id="staff_max_alert" class="<?=empty($customer['isDealer']) ? 'd-none' : ''?>">
<?php if (isset($customer['id'])){ ?>
*本季員工購物額度<?=$staff_max_amount?>元
<?php } else { ?>
*員工購物首次消費金額不得超過<?=$staff_max_amount?>元
<?php } ?>
<input type="hidden" id="staff_max_amount" value="<?= $staff_max_amount ?>" />
</div>
<?php if (!$isOld && !isset($customer['id'])) { ?>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="hide_customer_info" name="hide_customer_info" value="1"<?php if (set_value('hide_customer_info') == 1){ echo 'checked';}?>>
<label class="form-check-label" for="hide_customer_info">顧客無留下完整資料</label>
</div>
<?php } ?>
<div id="reason_wrap" class="d-none">
<label class="font-weight-bold">顧客為何無留下完整資料</label>
<textarea rows="4" name="reason" class="form-control"><?= set_value('reason') ?></textarea>
</div>
</div>
</div>
<div class="my-4">
<?php if ($customer && $customer['level']){ ?>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="promote_type[]" id="promote_type1" value="1">
<label class="form-check-label" for="promote_type1">
會員優惠
</label>
</div>
<?php } ?>
<?php if ($promotes){ ?>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="promote_type[]" id="promote_type2" value="2">
<label class="form-check-label" for="promote_type2">
優惠活動
<select id="promote_id" name="promote_id" class="form-control">
<option></option>
<?php foreach ($promotes as $promote_id => $promote) { ?>
<option value="<?= $promote_id ?>" data-customer_type="<?=$promote['customer_type']?>">
<?= $promote['title'] ?>
<?php
if ($promote['customer_type'] == 3){
echo '(員工活動)';
}
?>
</option>
<?php } ?>
</select>
</label>
</div>
<?php } ?>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="promote_type[]" id="promote_type3" value="3">
<label class="form-check-label" for="promote_type3">
使用貴賓優惠券
<input class="form-control" placeholder="輸入券號" name="coupon_used" />
</label>
</div>
</div>
<h3 class="mb-2 mt-4">一般商品</h3>
<table class="table table-hover table-bordered">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價</th>
<?php if ($dealer['hasStock']){ ?>
<th>庫存量</th>
<?php } ?>
<th>訂購數量</th>
<th>金額小計</th>
<th>折扣</th>
<th>折扣價</th>
</tr>
<?php if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr class="product_item" data-id="<?= $product_id ?>">
<td class="text-center"><?= $i ?></td>
<td><?= $product['p_num'] ?></td>
<td class="item_name"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
<td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
<?php if ($dealer['hasStock']){ ?>
<td class="text-right"><?= $product['stock'] ?></td>
<?php } ?>
<td>
<div class="input-group input-group-sm">
<input type="number" min="0" name="items[<?= $product_id ?>][qty]"
class="form-control text-right itemQty"
data-product_id="<?= $product_id ?>"
data-price="<?= intval($product['pdCash']) ?>"
<?php if ($dealer['hasStock']) { ?>
max="<?= $product['stock'] ?>"
data-expired_at="<?= $product['expired_at'] ?>"
<?php if (!$product['stock']){ ?>
disabled
placeholder="無庫存"
<?php } ?>
<?php } ?>
data-pao_month="<?= !empty($product['pao']) ? $product['pao']['pao_month'] : '' ?>"
value="<?= set_value('items[' . $product_id . '][qty]', '') ?>"/>
</div>
</td>
<td class="item_subtotal text-right"></td>
<td class="item_discount text-right" data-discount=""></td>
<td class="item_total text-right"></td>
</tr>
<?php
$i++;
}
}
?>
</table>
<?php if ($combos) { ?>
<h3 class="mb-2 mt-4">組合商品</h3>
<table class="table table-hover table-bordered">
<tr>
<th>名稱</th>
<th>明細</th>
<th>總金額</th>
<?php if ($dealer['hasStock']){ ?>
<th>庫存量</th>
<?php } ?>
<th>訂購數量</th>
<th>金額小計</th>
<th>折扣</th>
<th>折扣價</th>
</tr>
<?php
$i = 1;
foreach ($combos as $combo_id => $combo) {
?>
<tr class="combo_item" data-id="<?= $combo_id ?>">
<td><?= $combo['name'] ?></td>
<td>
<ol>
<?php
foreach ($combo['items'] as $item){
?>
<li class="combo_item_name" data-id="<?=$item['product']['pdId']?>" data-name="<?=$item['product']['pdName'] . $item['product']['intro2'] ?>" data-qty="<?=$item['qty'] ?>" data-price="<?= intval($item['price']) ?>" data-pao_month="<?= !empty($item['product']['pao']) ? $item['product']['pao']['pao_month'] : '' ?>">
<?=$item['product']['pdName'] . $item['product']['intro2'] . ' X' . $item['qty'] ?>
</li>
<?php
}
?>
</ol>
</td>
<td class="text-right"><?= '$' . number_format($combo['total']) ?></td>
<?php if ($dealer['hasStock']){ ?>
<td class="text-right"><?= $combo['stock'] ?></td>
<?php } ?>
<td>
<div class="input-group input-group-sm">
<input type="number" min="0" name="combo_items[<?= $combo_id ?>][qty]"
class="form-control text-right combo_itemQty"
data-price="<?= intval($combo['total']) ?>"
data-combo_id="<?= $combo_id ?>"
<?php if ($dealer['hasStock']) { ?>
max="<?= $combo['stock'] ?>"
<?php if (!$combo['stock']){ ?>
disabled
placeholder="無庫存"
<?php } ?>
<?php } ?>
value="<?= set_value('combo_items[' . $combo_id . '][qty]', '') ?>"/>
</div>
</td>
<td class="combo_item_subtotal text-right"></td>
<td class="combo_item_discount text-right" data-discount=""></td>
<td class="combo_item_total text-right"></td>
</tr>
<?php
$i++;
}
?>
</table>
<?php } ?>
<section id="gift-section" class="d-none">
<h3 class="mb-2 mt-4">贈品</h3>
<table class="table table-hover table-bordered">
<thead>
<tr>
<th>貨品名稱</th>
<th>贈品選擇</th>
</tr>
</thead>
<tbody></tbody>
</table>
</section>
<?php if ($free_packages) { ?>
<h3 class="mb-2 mt-4">免費包裝商品</h3>
<table class="table table-hover table-bordered">
<tr>
<th>貨品編號</th>
<th>貨品名稱</th>
<?php if ($dealer['hasStock']){ ?>
<th>庫存量</th>
<?php } ?>
<th>訂購數量</th>
</tr>
<?php
$i = 1;
foreach ($free_packages as $product_id => $free_package) {
?>
<tr>
<td><?= $free_package['product']['p_num'] ?></td>
<td class="package_name"><?= $free_package['product']['pdName'] . $free_package['product']['intro2']?></td>
<?php if ($dealer['hasStock']){ ?>
<td class="text-right"><?= $free_package['stock'] ?></td>
<?php } ?>
<td>
<div class="input-group input-group-sm">
<input type="number" min="0" name="package_items[<?= $product_id ?>][qty]"
class="form-control text-right package_itemQty"
data-product_id="<?= $product_id ?>"
<?php if ($dealer['hasStock']) { ?>
max="<?= $free_package['stock'] ?>"
<?php if (!$free_package['stock']){ ?>
disabled
placeholder="無庫存"
<?php } ?>
<?php } ?>
data-pao_month="<?= !empty($free_package['product']['pao']) ? $free_package['product']['pao']['pao_month'] : '' ?>"
value="<?= set_value('package_items[' . $product_id . '][qty]', '') ?>"/>
</div>
</td>
</tr>
<?php
$i++;
}
?>
</table>
<?php } ?>
<table class="table table-hover table-bordered mt-4">
<tr>
<td class="text-right font-weight-bold">小計</td>
<td id="subtotal_text" class="text-right font-weight-bold"></td>
</tr>
<tr id="totalDiscount" class="d-none">
<td class="text-right font-weight-bold">優惠折扣金額</td>
<td id="totalDiscount_text" class="text-right font-weight-bold"></td>
</tr>
<tr id="totalReachDiscount" class="d-none">
<td class="text-right font-weight-bold">滿額折扣</td>
<td id="totalReachDiscount_text" class="text-right font-weight-bold"></td>
</tr>
<tr>
<td class="text-right font-weight-bold">總計</td>
<td id="total_text" data-total="" class="text-right font-weight-bold"></td>
</tr>
<tr>
<td class="text-right font-weight-bold">備註</td>
<td>
<textarea rows="4" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
</td>
</tr>
</table>
<table class="table table-hover table-bordered mt-4">
<tr id="coupon_info" class="d-none">
<td colspan="3">
<p>「皮瑪斯九折優惠券」說明:</p>
<p>一.取得辦法:</p>
<ol>
<li>單筆消費「一顆橄欖」商品「2000元以上(含2000元)、未滿6000元」,則發放「皮瑪斯九折優惠券」乙張。</li>
<li>單筆消費「一顆橄欖」商品「6000元以上(含6000元)」,則發放「皮瑪斯九折優惠券」貳張。</li>
</ol>
<p>二.使用辦法:</p>
<ol>
<li>本券需於「皮瑪斯工坊門市」委託護理時提出;一張優惠券僅適用一物件,並依當時價格表之「九折」優惠計費。</li>
<li>本券可移轉他人使用,係「認券不認人」;使用優惠券,應於委託護理時付清費用。</li>
<li>需依皮瑪斯書面公告,本券方可併用其他優惠。</li>
<li>本券需經皮瑪斯驗證,方屬有效。</li>
</ol>
</td>
</tr>
<tr id="coupon_1" class="d-none">
<td class="text-right font-weight-bold">滿$2000核發折價券</td>
<td class="text-right font-weight-bold">折價券號</td>
<td>
<input disabled name="coupon_number_1" class="form-control" value="" />
</td>
</tr>
<tr id="coupon_2" class="d-none">
<td class="text-right font-weight-bold">滿$6000核發折價券</td>
<td class="text-right font-weight-bold">折價券號</td>
<td>
<input disabled name="coupon_number_2" class="form-control" value="" />
</td>
</tr>
</table>
<div class="mt-4 mb-2">
<div class="form-group">
<label class="font-weight-bold">付款方式</label>
<?php
echo form_dropdown('payment_type', $payment_type, set_value('payment_type'), 'id="payment_type" class="form-control"');
?>
</div>
<div id="recipient_info" class="d-none">
<div class="form-group">
<label class="font-weight-bold">收件人姓名</label>
<input name="recipient_name" class="form-control"
value="<?= set_value('recipient_name') ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">收件人電話</label>
<input name="recipient_phone" class="form-control"
value="<?= set_value('recipient_phone') ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">收件人地址</label>
<input name="recipient_address" class="form-control"
value="<?= set_value('recipient_address') ?>"/>
</div>
</div>
<div id="shipout_info" class="d-none">
<div class="form-group">
<label class="font-weight-bold">其他門市取貨</label>
<select id="shipout_retailer_id" name="shipout_retailer_id" class="form-control">
<option value=""></option>
<?php foreach ($shipout_retailers as $retailer_id => $retailer) { ?>
<option value="<?= $retailer_id ?>"><?= $retailer['company'] ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<input type="hidden" id="member_discount" value="<?= $member_discount ?>">
<div id="expired_submit_wrap" class="form-group text-center">
<button type="button" id="btn-checkout" class="btn btn-success">
填寫商品有效期限
</button>
</div>
<div id="direct_submit_wrap" class="form-group text-center d-none">
<input type="submit" name="submit_recommend" class="btn btn-success mr-auto" value="送出消費紀錄/進行推薦作業"/>
<input type="submit" name="submit_wo_recommend" class="btn btn-success" value="送出消費紀錄/不進行推薦作業"/>
</div>
<div class="modal fade" id="productExpirationModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">填寫商品有效期限</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table class="table table-bordered">
<thead>
<tr>
<th>貨品名稱</th>
<td>數量</td>
<td>有效期限</td>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div class="modal-footer">
<input type="submit" name="submit_recommend" class="btn btn-success mr-auto" value="送出消費紀錄/進行推薦作業"/>
<input type="submit" name="submit_wo_recommend" class="btn btn-success" value="送出消費紀錄/不進行推薦作業"/>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<link rel="stylesheet" href="<?= base_url('/css/datepicker.min.css')?>" />
<script src="<?= base_url('/js/datepicker.min.js')?>"></script>
<script>
var promotes = <?=json_encode($promotes)?>;
$().ready(function () {
$('#payment_type').change(function(){
var payment_type = parseInt($(this).val());
switch (payment_type){
case 4: //貨到付款
$('#recipient_info').removeClass('d-none');
$('#shipout_info').addClass('d-none');
$('#expired_submit_wrap').addClass('d-none');
$('#direct_submit_wrap').removeClass('d-none');
break;
case 5: //其他門市取貨
$('#recipient_info').addClass('d-none');
$('#shipout_info').removeClass('d-none');
$('#expired_submit_wrap').addClass('d-none');
$('#direct_submit_wrap').removeClass('d-none');
break;
default:
$('#recipient_info').addClass('d-none');
$('#shipout_info').addClass('d-none');
$('#expired_submit_wrap').removeClass('d-none');
$('#direct_submit_wrap').addClass('d-none');
break;
}
});
$('#payment_type').trigger('change');
$('#hide_customer_info').change(function(){
if ($(this).prop('checked')){
$('#customer_info').addClass('d-none');
$('#customer_info input').prop('disabled', true);
$('#customer_info select').prop('disabled', true);
$('#reason_wrap').removeClass('d-none');
} else {
$('#customer_info').removeClass('d-none');
$('#customer_info input').prop('disabled', false);
$('#customer_info select').prop('disabled', false);
$('#reason_wrap').addClass('d-none');
}
});
$('#hide_customer_info').trigger('change');
$('#isDealer').change(function(){
if ($(this).prop('checked')){
$('#staff_max_alert').removeClass('d-none');
$.each($('#promote_id option'), function(){
$(this).prop('disabled', false);
});
} else {
$('#staff_max_alert').addClass('d-none');
$.each($('#promote_id option'), function(){
if ($(this).data('customer_type') == '3'){
if ($('#promote_type2').prop('checked')){
if ($(this).prop("selected")){
$('#promote_type2').prop('checked', false);
$(this).prop("selected", false);
calc_total();
}
} else {
$(this).prop("selected", false);
}
$(this).prop('disabled', true);
}
});
}
});
$('#isDealer').trigger('change');
$("#birthday").datepicker({
format: 'mm/dd'
});
$('#btn-firstTime').click(function(){
$(this).parent().remove();
$('#order_wrap').removeClass('d-none');
});
calc_total();
$('a.show_picture').tooltip({
animated: 'fade',
placement: 'top',
html: true
});
$('#promote_type1').change(function () {
var selected_promote_id = $('#promote_id').val();
if (!selected_promote_id){
$('#promote_type3').prop('checked', false);
} else if (promotes[selected_promote_id]){
var go_with_member = parseInt(promotes[selected_promote_id]['go_with_member']) || 0;
if ($('#promote_type2').prop('checked') && !go_with_member){
$('#promote_type2').prop('checked', false);
}
$('#promote_type3').prop('checked', false);
calc_total();
} else {
alert('請選擇優惠活動');
}
});
$('#promote_type2').change(function () {
var selected_promote_id = $('#promote_id').val();
if (promotes[selected_promote_id]){
var go_with_member = parseInt(promotes[selected_promote_id]['go_with_member']) || 0;
if ($('#promote_type1').prop('checked') && !go_with_member){
$('#promote_type1').prop('checked', false);
}
var go_with_coupon = parseInt(promotes[selected_promote_id]['go_with_coupon']) || 0;
if ($('#promote_type3').prop('checked') && !go_with_coupon){
$('#promote_type3').prop('checked', false);
}
calc_total();
} else {
alert('請選擇優惠活動');
}
});
$('#promote_type3').change(function () {
var selected_promote_id = $('#promote_id').val();
if (!selected_promote_id) {
$('#promote_type1').prop('checked', false);
} else if (promotes[selected_promote_id]){
var go_with_coupon = parseInt(promotes[selected_promote_id]['go_with_coupon']) || 0;
if ($('#promote_type2').prop('checked') && !go_with_coupon){
$('#promote_type2').prop('checked', false);
}
$('#promote_type1').prop('checked', false);
calc_total();
} else {
alert('請選擇優惠活動');
}
});
$('#orderForm input.itemQty, #orderForm input.combo_itemQty, #promote_id').change(function () {
calc_total();
});
function calc_total() {
var subtotal = 0;
var total = 0;
var totalDiscount = 0;
var totalReachDiscount = 0;
var discount_type = 'P';
var discount = 100;
var promote = [];
if ($('#promote_type1').prop('checked')){
discount = parseInt($('#member_discount').val()) || 100;
}
for (var pk in promotes) {
for (var mk in promotes[pk]['methods']) {
promotes[pk]['methods'][mk]['totalDiscount'] = 0;
promotes[pk]['methods'][mk]['totalGift'] = 0;
}
}
$('#gift-section table tbody').html('');
$('#gift-section').addClass('d-none');
$('#subtotal_text').text('');
$('#total_text').text('');
$('#totalDiscount_text').text('');
$('#totalDiscount').addClass('d-none');
$('#totalReachDiscount_text').text('');
$('#totalReachDiscount').addClass('d-none');
$('#orderForm input.itemQty').each(function () {
var item = $(this).parents('tr');
var qty = parseInt($(this).val()) || 0;
var price = parseInt($(this).data('price'));
var product_id = parseInt($(this).data('product_id'));
var item_discount = discount;
var item_discount_type = discount_type;
if (qty > 0) {
var item_subtotal = qty * price;
if (item_discount_type == 'P') {
var item_total = Math.round(item_subtotal * item_discount / 100);
} else {
var item_total = item_subtotal - item_discount;
item_discount = Math.round(item_total / item_subtotal * 100);
}
if ($('#promote_type2').prop('checked')) {
var selected_promote_id = $('#promote_id').val();
promote = promotes[selected_promote_id];
if (promote) {
for (var key in promote['methods']) {
var method = promote['methods'][key];
switch (method['promote_type_id']) {
case '1': //產品折扣
var item_match = false;
if (method['items'] && method['items'].length) {
for (var ki in method['items']) {
var pitem = method['items'][ki];
if (pitem['id'] == product_id) {
item_match = true;
break;
}
}
} else {
item_match = true;
}
if (item_match) {
if (method['discount_type'] == 'P') {
item_total = Math.round(item_total * method['discount'] / 100);
item_discount = Math.round(item_total / item_subtotal * 100);
} else {
item_total -= method['discount'];
item_discount = Math.round(item_total / item_subtotal * 100);
}
}
break;
case '2': //滿額折扣
var item_match = false;
if (method['items'] && method['items'].length) {
for (var ki in method['items']) {
var pitem = method['items'][ki];
if (pitem['id'] == product_id) {
item_match = true;
break;
}
}
} else {
item_match = true;
}
if (item_match) {
promote['methods'][key]['totalDiscount'] += item_total;
}
break;
case '3': //贈品
var item_match = false;
if (method['relatives'] && method['relatives'].length) {
for (var ki in method['relatives']) {
var pitem = method['relatives'][ki];
if (pitem['type'] == 'product' && pitem['id'] == product_id) {
item_match = true;
break;
}
}
} else {
item_match = true;
}
if (item_match) {
if (!('totalGift' in promote['methods'][key])) {
promote['methods'][key]['totalGift'] = 0;
}
promote['methods'][key]['totalGift'] += item_total;
}
break;
}
}
}
}
subtotal += item_subtotal;
totalDiscount += item_subtotal - item_total;
total += item_total;
} else {
item_subtotal = 0;
item_total = 0;
}
item.find('.item_discount').text(item_discount + '%').data('discount', item_discount);
item.find('.item_subtotal').text('$' + numberWithCommas(item_subtotal));
item.find('.item_total').text('$' + numberWithCommas(item_total));
});
$('#orderForm input.combo_itemQty').each(function () {
var item = $(this).parents('tr');
var qty = parseInt($(this).val()) || 0;
var price = parseInt($(this).data('price'));
var combo_id = parseInt($(this).data('combo_id'));
var combo_item_discount = discount;
var combo_item_discount_type = discount_type;
if (qty > 0) {
var combo_item_subtotal = qty * price;
if (combo_item_discount_type == 'P') {
var combo_item_total = Math.round(combo_item_subtotal * combo_item_discount / 100);
} else {
var combo_item_total = combo_item_subtotal - combo_item_discount;
combo_item_discount = Math.round(combo_item_total / combo_item_subtotal * 100);
}
if ($('#promote_type2').prop('checked')) {
var selected_promote_id = $('#promote_id').val();
promote = promotes[selected_promote_id];
if (promote) {
for (var key in promote['methods']) {
var method = promote['methods'][key];
switch (method['promote_type_id']) {
case '1': //產品折扣
var item_match = false;
if (method['items'] && method['items'].length) {
for (var ki in method['items']) {
var pitem = method['items'][ki];
if (pitem['type'] == 'combo' && pitem['id'] == combo_id) {
item_match = true;
break;
}
}
} else {
item_match = true;
}
if (item_match) {
if (method['discount_type'] == 'P') {
combo_item_total = Math.round(combo_item_total * method['discount'] / 100);
combo_item_discount = Math.round(combo_item_total / combo_item_subtotal * 100);
} else {
combo_item_total -= method['discount'];
combo_item_discount = Math.round(combo_item_total / combo_item_subtotal * 100);
}
}
break;
case '2': //滿額折扣
var item_match = false;
if (method['items'] && method['items'].length) {
for (var ki in method['items']) {
var pitem = method['items'][ki];
if (pitem['type'] == 'combo' && pitem['id'] == combo_id) {
item_match = true;
break;
}
}
} else {
item_match = true;
}
if (item_match) {
promote['methods'][key]['totalDiscount'] += combo_item_total;
}
break;
case '3': //贈品
var item_match = false;
if (method['relatives'] && method['relatives'].length) {
for (var ki in method['relatives']) {
var pitem = method['relatives'][ki];
if (pitem['type'] == 'combo' && pitem['id'] == combo_id) {
item_match = true;
break;
}
}
} else {
item_match = true;
}
if (item_match) {
promote['methods'][key]['totalGift'] += combo_item_total;
}
break;
}
}
}
}
subtotal += combo_item_subtotal;
totalDiscount += combo_item_subtotal - combo_item_total;
total += combo_item_total;
} else {
combo_item_subtotal = 0;
combo_item_total = 0;
}
item.find('.combo_item_discount').text(combo_item_discount + '%').data('discount', combo_item_discount);
item.find('.combo_item_subtotal').text('$' + numberWithCommas(combo_item_subtotal));
item.find('.combo_item_total').text('$' + numberWithCommas(combo_item_total));
});
if (promote){
var gift_html = '';
for (var key in promote['methods']) {
var method = promote['methods'][key];
switch (method['promote_type_id']){
case '2': //滿額折扣
if ('totalDiscount' in method && method['totalDiscount'] >= method['limit']) {
totalReachDiscount += parseInt(method['discount']);
}
break;
case '3': //贈品
if ('totalGift' in method && method['totalGift'] >= method['limit']) {
for (var ki in method['items']) {
var pitem = method['items'][ki];
gift_html += '<tr>';
gift_html += '<td>' + pitem['name'] + '</td>';
gift_html += '<td class="gift_qty text-right">';
if (method['options'] && method['options']['single']){
gift_html += '<input type="radio" id="gifts-' + method['id'] + '-' + pitem['type'] + '-' + pitem['id'] + '" class="gift_itemQty" name="gifts[' + method['id'] + ']" value="' + pitem['type'] + '-' + pitem['id'] + '" checked data-method="' + method['id'] + '" data-type="' + pitem['type'] + '" data-id="' + pitem['id'] + '" data-pao_month="' + pitem['pao_month'] + '" />';
} else {
gift_html += '1<input type="hidden" class="gift_itemQty" data-method="' + method['id'] + '" data-type="' + pitem['type'] + '" data-id="' + pitem['id'] + '" data-pao_month="' + pitem['pao_month'] + '" value="1" />';
}
gift_html += '</td>';
gift_html += '</tr>';
}
}
break;
}
}
total -= totalReachDiscount;
if (gift_html) {
$('#gift-section table tbody').html(gift_html);
$('#gift-section').removeClass('d-none');
}
}
$('#subtotal_text').text('$' + numberWithCommas(subtotal));
if (totalDiscount > 0){
$('#totalDiscount_text').text('- $' + numberWithCommas(totalDiscount));
$('#totalDiscount').removeClass('d-none');
}
if (totalReachDiscount > 0){
$('#totalReachDiscount_text').text('- $' + numberWithCommas(totalReachDiscount));
$('#totalReachDiscount').removeClass('d-none');
}
$('#total_text').text('$' + numberWithCommas(total)).data('total', total);
checkCouponApprove(total);
}
});
function checkCouponApprove(total){
$('#coupon_info').addClass('d-none');
$('#coupon_1').addClass('d-none').find('input').prop('disabled', true).val('');
$('#coupon_2').addClass('d-none').find('input').prop('disabled', true).val('');
if (total >= 2000){
$('#coupon_info').removeClass('d-none');
$('#coupon_1').removeClass('d-none').find('input').prop('disabled', false);
if (total >= 6000){
$('#coupon_2').removeClass('d-none').find('input').prop('disabled', false);
}
}
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$("#orderForm").keydown(function(e){
if(e.keyCode == 13) {
e.preventDefault();
return false;
}
});
$('#btn-checkout').click(function(){
var hasQty = false;
$.each($('input.itemQty'), function () {
if ($(this).val() > 0) {
hasQty = true;
return false;
}
});
if (!hasQty) {
$.each($('input.combo_itemQty'), function () {
if ($(this).val() > 0) {
hasQty = true;
return false;
}
});
}
if (!hasQty) {
alert('您尚未選購商品');
} else {
var expiration_html = '';
$('#orderForm input.itemQty').each(function () {
var qty = parseInt($(this).val()) || 0;
if (qty > 0) {
var item = $(this).parents('tr');
var product_name = item.find('td.item_name').text();
var item_discount = item.find('td.item_discount').data('discount');
var product_id = parseInt($(this).data('product_id'));
var pao_month = parseInt($(this).data('pao_month'));
var price = parseInt($(this).data('price'));
var expired_at = $(this).data('expired_at');
var item_total = Math.round(price * item_discount / 100);
for (var i = 0; i < qty; i++) {
expiration_html += '<tr>' +
'<td>' + product_name + '</td>' +
'<td>1</td>' +
'<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="' + item_total + '" value="' + expired_at + '" /></td>' +
'</tr>';
}
}
});
$('#orderForm input.combo_itemQty').each(function () {
var item = $(this).parents('tr');
var combo_qty = parseInt($(this).val()) || 0;
var combo_id = parseInt($(this).data('combo_id')) || 0;
if (combo_qty > 0 && combo_id > 0) {
item.find('li.combo_item_name').each(function () {
var product_name = $(this).data('name');
var product_id = parseInt($(this).data('id'));
var product_qty = parseInt($(this).data('qty')) || 0;
var pao_month = parseInt($(this).data('pao_month'));
var item_total = parseInt($(this).data('price'));
if (product_qty > 0) {
for (var i = 0; i < combo_qty * product_qty; i++) {
expiration_html += '<tr>' +
'<td>[組合]' + product_name + '</td>' +
'<td>1</td>' +
'<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="' + item_total + '" /></td>' +
'</tr>';
}
}
});
}
});
$('#orderForm input.package_itemQty').each(function () {
var qty = parseInt($(this).val()) || 0;
if (qty > 0) {
var item = $(this).parents('tr');
var pao_month = parseInt($(this).data('pao_month'));
var package_name = item.find('td.package_name').text();
var product_id = parseInt($(this).data('product_id'));
for (var i = 0; i < qty; i++) {
expiration_html += '<tr>' +
'<td>[包裝]' + package_name + '</td>' +
'<td>1</td>' +
'<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="0" /></td>' +
'</tr>';
}
}
});
$('#orderForm input.gift_itemQty').each(function () {
if ($(this).prop('type') == 'hidden' || ($(this).prop('type') == 'radio' && $(this).prop('checked') == true)) {
var gift_method = parseInt($(this).data('method')) || 0;
var gift_type = $(this).data('type');
var gift_id = parseInt($(this).data('id')) || 0;
if (gift_method > 0 && gift_id > 0) {
if (gift_type == 'product') {
$.each($('tr.product_item'), function () {
var product_id = parseInt($(this).data('id')) || 0;
if (product_id > 0 && gift_id == product_id) {
var pao_month = parseInt($(this).data('pao_month'));
var product_name = $(this).find('td.item_name').text();
expiration_html += '<tr>' +
'<td>[贈品]' + product_name + '</td>' +
'<td>1</td>' +
'<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="0" /></td>' +
'</tr>';
return false;
}
});
} else if (gift_type == 'combo') {
$.each($('tr.combo_item'), function () {
var combo_id = parseInt($(this).data('id')) || 0;
if (combo_id > 0 && gift_id == combo_id) {
$(this).find('li.combo_item_name').each(function () {
var product_name = $(this).data('name');
var product_id = parseInt($(this).data('id'));
var product_qty = parseInt($(this).data('qty')) || 0;
var pao_month = parseInt($(this).data('pao_month'));
if (product_qty > 0) {
for (var i = 0; i < product_qty; i++) {
expiration_html += '<tr>' +
'<td>[贈品]' + product_name + '</td>' +
'<td>1</td>' +
'<td><input type="date" class="expired_dates" name="expired_dates[' + product_id + '][]" data-pao_month="' + pao_month + '" data-price="0" /></td>' +
'</tr>';
}
}
});
return false;
}
});
}
}
}
});
$('#productExpirationModal table tbody').html(expiration_html);
$('#productExpirationModal').modal('show');
}
});
$("#orderForm").find('input[type="submit"]').click(function (e) {
if ($('#isDealer').prop('checked')) {
var total = $('#total_text').data('total');
var staff_max_amount = $('#staff_max_amount').val();
$('#orderForm input.expired_dates').each(function () {
var expired_date = $(this).val();
var pao_month = parseInt($(this).data('pao_month')) || 0;
var price = parseInt($(this).data('price')) || 0;
if (expired_date && pao_month > 0 && price > 0){
var nd = new Date();
var xd = new Date(expired_date);
xd.setMonth(xd.getMonth() - pao_month);
if (nd.getTime() >= xd.getTime()){
total -= price;
}
}
});
if (total > staff_max_amount){
alert('超過員工購物消費金額');
return false;
}
}
if (confirm('請確認是否送出消費紀錄?')) {
$.each($('input.itemQty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('input.combo_itemQty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('input.package_itemQty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
} else {
return false;
}
});
</script><file_sep>/application/migrations/061_update_shipment_revise_id.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_shipment_revise_id extends CI_Migration {
public function up()
{
$this->dbforge->add_column('olive_shipments', [
'shipment_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'after' => 'id',
],
'isRevised' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'isConfirmed',
],
'isReturn' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'isRevised',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_shipments', 'shipment_id');
$this->dbforge->drop_column('olive_shipments', 'isRevised');
$this->dbforge->drop_column('olive_shipments', 'isReturn');
}
}<file_sep>/application/migrations/050_update_retailer_sales_dealer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_sales_dealer extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_retailers', [
'sales_dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
'after' => 'sales_retailer_id',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_retailers', 'sales_dealer_id');
}
}<file_sep>/application/models/Customer_level_model.php
<?php
class Customer_level_model extends MY_Model
{
public $table = 'olive_customer_levels';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['customers'] = array('Customer_model', 'customer_level_id', 'id');
}
public function getLevelSelect()
{
$_levels = $this
->order_by('id', 'asc')
->get_all();
$levels = [];
foreach ($_levels as $level){
$levels[$level['id']] = $level['title'];
}
return $levels;
}
public function getLevelFirstDiscount()
{
$level = $this
->order_by('id', 'asc')
->get();
return $level['discount'];
}
}
?>
<file_sep>/application/models/Purchase_model.php
<?php
class Purchase_model extends MY_Model
{
public $table = 'olive_purchases';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['items'] = array('Purchase_item_model', 'purchase_id', 'id');
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['shipin_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipin_retailer_id');
$this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
$this->has_one['confirm'] = array('foreign_model' => 'Confirm_model', 'foreign_table' => 'olive_confirms', 'foreign_key' => 'confirm_id', 'local_key' => 'id');
$this->has_many['payments'] = array('Payment_model', 'pay_id', 'id');
$this->has_many['shipments'] = array('Shipment_model', 'ship_id', 'id');
$this->has_one['transfer_to'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'transfer_id');
$this->has_one['transfer_from'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'transfer_id', 'local_key' => 'id');
$this->has_one['order_transfer'] = array('foreign_model' => 'Order_transfer_model', 'foreign_table' => 'olive_order_transfers', 'foreign_key' => 'purchase_id', 'local_key' => 'id');
}
public function getNextPurchaseSerialNum()
{
$purchase = $this
->with_trashed()
->where('DATE_FORMAT(created_at,"%Y-%m") = "' . date('Y-m') . '"', null, null, false, false, true)
->order_by('serialNum', 'desc')
->get();
if ($purchase) {
$num = (int)$purchase['serialNum'] + 1;
return str_pad($num, 5, '0', STR_PAD_LEFT);
} else {
return '00001';
}
}
public function checkHasAllowance($purchase_id)
{
$this->load->model('payment_model');
//銷貨折讓
$hasAllowance = false;
$payments = $this->payment_model
->where('pay_type', 'shipment_allowance')
->where('pay_id', $purchase_id)
->get_all();
if ($payments) {
foreach ($payments as $payment){
if (!$payment['active'] || !$payment['isConfirmed']){
$hasAllowance = true;
break;
}
}
}
if (!$hasAllowance){
$this->update([
'isAllowance' => 0,
], ['id' => $purchase_id]);
}
}
public function checkCorrect($purchase_id)
{
$purchase = $this
->get($purchase_id);
if ($purchase['isShipped'] && !$purchase['isRevised']){
$this->update(['isShipConfirmed' => 1], ['id' => $purchase_id]);
$this->load->model('commission_model');
$this->commission_model->record($purchase_id);
}
}
public function transfer_purchase($purchase_id, $new_shipout_retailer_id, $dealer)
{
$purchase = $this->purchase_model
->with_transfer_from()
->with_shipout_retailer('fields:company,invoice_title,address')
->with_items()
->get($purchase_id);
if ($purchase['retailer_id'] == $new_shipout_retailer_id || $purchase['shipin_retailer_id'] == $new_shipout_retailer_id){
return false;
}
$new_retailer_id = $purchase['shipout_retailer_id'];
$new_retailer = $purchase['shipout_retailer'];
if (empty($purchase['transfer_from'])){
$new_shipin_retailer_id = $purchase['shipin_retailer_id'];
$new_shipin_address = $purchase['shipin_address'];
} else {
$new_shipin_retailer_id = $purchase['transfer_from']['shipout_retailer_id'];
$new_shipin_address = $purchase['transfer_from']['shipout_retailer']['address'];
}
$purchaseSerialNum = $this->getNextPurchaseSerialNum();
$insert_data = [
'retailer_id' => $new_retailer_id,
'retailer_address' => $new_retailer['address'],
'shipout_retailer_id' => $new_shipout_retailer_id,
'shipin_retailer_id' => $new_shipin_retailer_id,
'shipin_address' => $new_shipin_address,
'serialNum' => $purchaseSerialNum,
'purchaseNum' => date('Ym') . $purchaseSerialNum,
'memo' => $purchase['memo'],
'isInvoice' => $purchase['isInvoice'],
'dealer_id' => $dealer['id'],
];
if ($purchase['isInvoice']) {
$insert_data['invoice_retailer'] = $new_retailer['invoice_title'];
$insert_data['invoice_send_retailer'] = $new_retailer['invoice_title'];
$insert_data['invoice_send_address'] = $new_retailer['address'];
}
$new_purchase_id = $this->insert($insert_data);
//計算折扣
$this->load->model('retailer_relationship_model');
$relative_shipout_retailer = $this->retailer_relationship_model
->where('relation_type', 'shipout')
->where('retailer_id', $new_retailer_id)
->where('relation_retailer_id', $new_shipout_retailer_id)
->get();
$discount = 100;
if ($relative_shipout_retailer){
if ($relative_shipout_retailer['discount']){
$discount = $relative_shipout_retailer['discount'];
}
}
if ($purchase['isInvoice']) {
$relative_invoice_retailer = $this->retailer_relationship_model
->where('relation_type', 'invoice')
->where('retailer_id', $new_retailer_id)
->where('relation_retailer_id', $new_shipout_retailer_id)
->where('alter_retailer_id', $new_retailer_id)
->get();
if ($relative_invoice_retailer){
if ($relative_invoice_retailer['discount']){
$discount = $relative_invoice_retailer['discount'];
}
}
}
//產品的出貨折扣
$this->load->model('product_relationship_model');
$relationship_products = $this->product_relationship_model->getRelationshipProducts($new_retailer_id, $new_shipout_retailer_id);
//儲存產品
$subtotal = 0;
$total = 0;
$this->load->model('purchase_item_model');
$items = $purchase['items'];
foreach ($items as $item) {
$product_id = $item['product_id'];
$qty = $item['qty'];
$price = $item['price'];
$item_discount = empty($relationship_products[$product_id]) ? $discount : $relationship_products[$product_id];
$this->purchase_item_model->insert([
'purchase_id' => $new_purchase_id,
'product_id' => $product_id,
'price' => $price,
'qty' => $qty,
'subtotal' => $price * $qty,
'discount' => $item_discount,
'total' => floor($price * $item_discount / 100) * $qty,
]);
$subtotal += $price * $qty;
$total += floor($price * $item_discount / 100) * $qty;
}
$this->purchase_model->update([
'subtotal' => $subtotal,
'total' => $total,
], ['id' => $new_purchase_id]);
$this->load->model('payment_model');
$this->payment_model->insert([
'pay_type' => 'purchase',
'pay_id' => $new_purchase_id,
'paid_retailer_id' => $new_retailer_id,
'received_retailer_id' => $new_shipout_retailer_id,
'price' => $total,
'retailer_id' => $dealer['retailer_id'],
'dealer_id' => $dealer['id'],
'active' => 0,
]);
$this->purchase_model->update([
'transfer_id' => $new_purchase_id,
], ['id' => $purchase_id]);
return $new_purchase_id;
}
//計算銷貨折讓總額
public function sumPurchaseAllowance($purchase_id)
{
$allowance_payment_total = 0;
$this->load->model('payment_model');
$payments = $this->payment_model
->where('pay_type', 'shipment_allowance')
->where('pay_id', $purchase_id)
->where('active', 1)
->where('isConfirmed', 1)
->get_all();
if ($payments) {
foreach ($payments as $payment){
$allowance_payment_total += $payment['price'];
}
}
return $allowance_payment_total;
}
}
?>
<file_sep>/application/views/layout/blank.php
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="designer" content="cystudio, <EMAIL>" />
<title><?= $title ?></title>
<script src="<?= base_url('/js/jquery-3.2.1.slim.min.js')?>"></script>
<script src="<?= base_url('/js/popper.min.js')?>"></script>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M5LQ7CP');</script>
<script src="<?= base_url('/js/bootstrap.min.js')?>"></script>
<link href="<?= base_url('css/bootstrap.min.css') ?>" rel="stylesheet" type="text/css">
<link href="<?= base_url('css/styles.css') ?>" rel="stylesheet" type="text/css">
</head>
<body>
<?php
if (isset($data)) {
$this->load->view($view, $data);
} else {
$this->load->view($view);
}
?>
</body>
</html><file_sep>/application/models/Order_return_model.php
<?php
class Order_return_model extends MY_Model
{
public $table = 'olive_order_returns';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['items'] = array('Order_return_item_model', 'order_return_id', 'id');
$this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
}
}
?>
<file_sep>/application/controllers/Commission.php
<?php
class Commission extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('dealer_model');
$this->load->model('commission_model');
$this->load->model('retailer_model');
$this->load->model('retailer_relationship_model');
$this->session->set_userdata('return_page', base_url('/commission/overview'));
}
//輔銷人列表
public function dealers()
{
$_retailer_relationships = $this->retailer_relationship_model
->where('relation_retailer_id', $this->dealer['retailer_id'])
->where('relation_type', 'supervisor')
->get_all();
$retailer_relationships = [];
if ($_retailer_relationships){
foreach ($_retailer_relationships as $retailer_relationship){
array_push($retailer_relationships, $retailer_relationship['retailer_id']);
}
}
$retailers = [];
if ($retailer_relationships) {
$total_retailers_count = $this->retailer_model
->where('id', $retailer_relationships)
->count_rows();
$retailers = $this->retailer_model
->with_sales_retailer()
->with_sales_dealer()
->where('id', $retailer_relationships)
->paginate(20, $total_retailers_count);
}
$this->load->helper('data_format');
//權限設定
$authority = array();
if ($this->authentic->authority('commission', 'dealer')){
$authority['dealer'] = true;
}
$data = [
'retailers' => $retailers,
'authority' => $authority,
'title' => '輔銷人名單',
'view' => 'commission/dealers',
];
$this->_preload($data);
}
public function dealer($dealer_id, $commissionMonth = '')
{
// $retailer_relationship = $this->retailer_relationship_model
// ->where('retailer_id', $retailer_id)
// ->where('relation_retailer_id', $this->dealer['retailer_id'])
// ->where('relation_type', 'supervisor')
// ->get();
//
// if (!$retailer_relationship) {
// show_error('查無輔銷人資料!');
// }
//
// $retailer = $this->retailer_model
// ->with_sales_retailer()
// ->with_sales_dealer()
// ->get($retailer_id);
$dealer = $this->dealer_model
->get($dealer_id);
if (!$dealer) {
show_error('查無輔銷人資料!');
}
$c = $this->commission_model
->fields('SUM(' . $this->commission_model->get_table_name() . '.total) as total')
->where('commission_type', 'dealer')
->where('commission_id', $dealer_id)
->get();
$total_commission = $c['total'];
if (!$commissionMonth) $commissionMonth = date('Y-m-d', strtotime('first day of previous month'));
$first_day_commissionMonth = date('Y-m-01', strtotime($commissionMonth));
$last_day_commissionMonth = date('Y-m-t', strtotime($commissionMonth));
$_commissions = $this->commission_model
->with_purchase()
->where('commission_type', 'dealer')
->where('commission_id', $dealer_id)
->where('created_at', '>=', $first_day_commissionMonth)
->where('created_at', '<=', $last_day_commissionMonth)
->order_by($this->commission_model->get_table_name().'.created_at', 'desc')
->get_all();
$month_total_commission = 0;
$retailers = [];
if ($_commissions){
foreach ($_commissions as $commission) {
$retailer_id = $commission['purchase']['retailer_id'];
if (!isset($retailers[$retailer_id])){
$r = $this->retailer_model
->with_sales_retailer()
->with_sales_dealer()
->get($retailer_id);
if ($r) {
$r['subtotal'] = 0;
$r['commissions'] = [];
$retailers[$retailer_id] = $r;
}
}
$retailers[$retailer_id]['subtotal'] += $commission['total'];
$retailers[$retailer_id]['commissions'][] = $commission;
$month_total_commission += $commission['total'];
}
}
$commissionPrevMonth = date('Y-m-d', strtotime($commissionMonth . ' first day of previous month'));
$commissionNextMonth = date('Y-m-d', strtotime($commissionMonth . ' first day of next month'));
if (strtotime($commissionNextMonth) > time()){
$commissionNextMonth = '';
}
$data = [
'dealer' => $dealer,
'retailers' => $retailers,
'month_total_commission' => $month_total_commission,
'total_commission' => $total_commission,
'commissionMonth' => date('Y/m', strtotime($commissionMonth)),
'prevMonthUrl' => base_url('/commission/dealer/' . $dealer_id . '/' . $commissionPrevMonth),
'nextMonthUrl' => $commissionNextMonth ? base_url('/commission/dealer/' . $dealer_id . '/' . $commissionNextMonth) : '',
'title' => '輔銷人獎金',
'view' => 'commission/dealer',
];
$this->_preload($data);
}
}
?><file_sep>/application/controllers/Capital_stock.php
<?php
class Capital_stock extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('stock_model');
$this->load->model('retailer_model');
$this->load->model('product_model');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/capital_stock/overview'));
}
public function overview($retailer_id = '')
{
$retailer_selects = $this->retailer_model->getRetailerSelect();
$retailer = [];
$products = [];
if ($retailer_id) {
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer){
show_error('查無經銷單位資料');
}
$products = $this->product_model->getUnitProductStocks($retailer_id);
}
//權限設定
$authority = array();
if ($this->authentic->authority('capital_stock', 'detail')){
$authority['detail'] = true;
}
$data = [
'retailer_id' => $retailer_id,
'retailer_selects' => $retailer_selects,
'retailer' => $retailer,
'products' => $products,
'authority' => $authority,
'title' => '庫存列表',
'view' => 'capital/stock/overview',
];
$this->_preload($data);
}
public function detail($retailer_id, $product_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer){
show_error('查無經銷單位資料');
}
$product = $this->product_model
->with_pao()
->where('pKind', [3,6])
->where('pEnable', 'Y')
->where('pdId', $product_id)
->get();
if (!$product_id || !$product) {
show_error('查無經銷單位商品資料!');
}
$stocks = $this->stock_model
->where('product_id', $product['pdId'])
->where('retailer_id', $retailer_id)
->where('stock', '>', 0)
->order_by('expired_at', 'asc')
->get_all();
$product['stock'] = $this->product_model->calcStock($stocks, $product);
$data = [
'retailer' => $retailer,
'product' => $product,
'title' => '詳細產品庫存資訊',
'view' => 'capital/stock/detail',
];
$this->_preload($data);
}
}
?><file_sep>/application/controllers/Income.php
<?php
class Income extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('dealer_model');
$this->load->model('commission_model');
$this->load->model('payment_model');
$this->load->model('expense_model');
$this->session->set_userdata('return_page', base_url('/capital_income/overview'));
}
public function overview()
{
$this->load->model('retailer_relationship_model');
$retailers = $this->retailer_relationship_model
->with_retailer()
->where('relation_retailer_id', $this->dealer['retailer_id'])
->where('relation_type', 'supervisor')
->get_all();
$search = array(
'retailer_id' => (int)$this->input->get('retailer_id'),
'created_start' => strtotime($this->input->get('created_start')) > 0 ? $this->input->get('created_start') : date('Y-m-01'),
'created_end' => strtotime($this->input->get('created_end')) > 0 ? $this->input->get('created_end') : date('Y-m-t'),
);
if ($search['retailer_id']){
$retailer_relationship = $this->retailer_relationship_model
->where('retailer_id', $search['retailer_id'])
->where('relation_retailer_id', $this->dealer['retailer_id'])
->where('relation_type', 'supervisor')
->get();
if (!$retailer_relationship){
show_error('查無單位資料!');
}
$retailer_id = $search['retailer_id'];
} else {
$retailer_id = $this->dealer['retailer_id'];
}
$income = [
'revenue' => [],
'expense' => [],
'total' => 0,
];
if ($retailer_id) {
$payment_table = $this->payment_model->get_table_name();
//出貨收益
$data = $this->payment_model
->fields('SUM(' . $payment_table . '.price) as total')
->where('received_retailer_id', $retailer_id)
->where('pay_type', 'purchase')
->where('isConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['revenue'][] = [
'name' => '出貨收益',
'total' => $data['total']
];
$income['total'] += $data['total'];
}
//進貨銷貨折讓
$data = $this->payment_model
->fields('SUM(' . $payment_table . '.price) as total')
->where('received_retailer_id', $retailer_id)
->where('pay_type', 'shipment_allowance')
->where('isConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['revenue'][] = [
'name' => '進貨銷貨折讓',
'total' => $data['total']
];
$income['total'] += $data['total'];
}
//消費者訂單收益
$data = $this->payment_model
->fields('SUM(' . $payment_table . '.price) as total')
->where('received_retailer_id', $retailer_id)
->where('pay_type', 'order')
->where('isConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['revenue'][] = [
'name' => '消費者訂購',
'total' => $data['total']
];
$income['total'] += $data['total'];
}
//輔銷獎金收益
$data = $this->commission_model
->fields('SUM(' . $this->commission_model->get_table_name() . '.total) as total')
->where('commission_type', 'retailer')
->where('commission_id', $retailer_id)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['revenue'][] = [
'name' => '輔銷獎金收益',
'total' => $data['total']
];
$income['total'] += $data['total'];
}
//進貨支出
$data = $this->payment_model
->fields('SUM(' . $payment_table . '.price) as total')
->where('paid_retailer_id', $retailer_id)
->where('pay_type', 'purchase')
->where('isConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['expense'][] = [
'name' => '進貨支出',
'total' => $data['total']
];
$income['total'] -= $data['total'];
}
//出貨銷貨折讓
$data = $this->payment_model
->fields('SUM(' . $payment_table . '.price) as total')
->where('paid_retailer_id', $retailer_id)
->where('pay_type', 'shipment_allowance')
->where('isConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['expense'][] = [
'name' => '出貨銷貨折讓',
'total' => $data['total']
];
$income['total'] -= $data['total'];
}
//輔銷獎金支出
$sales_retailers = $this->retailer_model
->where('sales_retailer_id', $retailer_id)
->get_all();
$sales_dealers = [];
if ($sales_retailers) {
foreach ($sales_retailers as $sales_retailer) {
array_push($sales_dealers, $sales_retailer['sales_dealer_id']);
}
}
if ($sales_dealers) {
$data = $this->commission_model
->fields('SUM(' . $this->commission_model->get_table_name() . '.total) as total')
->where('commission_type', 'dealer')
->where('commission_id', $sales_dealers)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['expense'][] = [
'name' => '輔銷獎金支出',
'total' => $data['total']
];
$income['total'] -= $data['total'];
}
}
//運費支出
$data = $this->expense_model
->fields('SUM(' . $this->expense_model->get_table_name() . '.price) as total')
->where('retailer_id', $retailer_id)
->where('expense_type', 'freight')
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['expense'][] = [
'name' => '運費支出',
'total' => $data['total']
];
$income['total'] -= $data['total'];
}
//手續費
$data = $this->expense_model
->fields('SUM(' . $this->expense_model->get_table_name() . '.price) as total')
->where('retailer_id', $retailer_id)
->where('expense_type', 'fare')
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get();
if (!empty($data['total'])) {
$income['expense'][] = [
'name' => '手續費支出',
'total' => $data['total']
];
$income['total'] -= $data['total'];
}
}
$data = [
'search' => $search,
'income' => $income,
'retailers' => $retailers,
'title' => '營業資訊',
'view' => 'income/overview',
];
$this->_preload($data);
}
public function product()
{
$this->load->model('retailer_relationship_model');
$retailers = $this->retailer_relationship_model
->with_retailer()
->where('relation_retailer_id', $this->dealer['retailer_id'])
->where('relation_type', 'supervisor')
->get_all();
$search = array(
'retailer_id' => (int)$this->input->get('retailer_id'),
'product_id' => (int)$this->input->get('product_id'),
'created_start' => strtotime($this->input->get('created_start')) > 0 ? $this->input->get('created_start') : date('Y-m-01'),
'created_end' => strtotime($this->input->get('created_end')) > 0 ? $this->input->get('created_end') : date('Y-m-t'),
);
if ($search['retailer_id']){
$retailer = $this->retailer_relationship_model
->where('retailer_id', $search['retailer_id'])
->where('relation_retailer_id', $this->dealer['retailer_id'])
->where('relation_type', 'supervisor')
->get();
if (!$retailer){
show_error('查無單位資料!');
}
$retailer_id = $search['retailer_id'];
} else {
$retailer_id = $this->dealer['retailer_id'];
}
$income = [
'revenue' => [],
'expense' => [],
'totalQty' => 0,
'total' => 0,
];
if ($retailer_id && $search['product_id']) {
$this->load->model('purchase_model');
$this->load->model('purchase_item_model');
$purchase_item_table = $this->purchase_item_model->get_table_name();
$purchases = $this->purchase_model
->with_items(['where' => "product_id='". $search['product_id'] . "'", 'fields' => 'SUM(' . $purchase_item_table . '.qty) as totalQty, SUM(' . $purchase_item_table . '.total) as total'])
->where('shipout_retailer_id', $retailer_id)
->where('isShipConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get_all();
if (!empty($purchases)) {
foreach ($purchases as $purchase){
$income['revenue'][] = [
'name' => '出貨售出',
'totalQty' => $purchase['items'][0]['totalQty'],
'total' => $purchase['items'][0]['total'],
];
$income['totalQty'] += $purchase['items'][0]['totalQty'];
$income['total'] += $purchase['items'][0]['total'];
}
}
$purchases = $this->purchase_model
->with_items(['where' => "product_id='". $search['product_id'] . "'", 'fields' => 'SUM(' . $purchase_item_table . '.qty) as totalQty, SUM(' . $purchase_item_table . '.total) as total'])
->where('shipin_retailer_id', $retailer_id)
->where('isShipConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get_all();
if (!empty($purchases)) {
foreach ($purchases as $purchase){
$income['revenue'][] = [
'name' => '進貨購入',
'totalQty' => $purchase['items'][0]['totalQty'],
'total' => $purchase['items'][0]['total'],
];
$income['totalQty'] -= $purchase['items'][0]['totalQty'];
$income['total'] -= $purchase['items'][0]['total'];
}
}
$this->load->model('order_model');
$this->load->model('order_item_model');
$order_item_table = $this->order_item_model->get_table_name();
$orders = $this->order_model
->with_items(['where' => "product_id='". $search['product_id'] . "'", 'fields' => 'SUM(' . $order_item_table . '.qty) as totalQty, SUM(' . $order_item_table . '.subPrice) as total'])
->where('shipout_retailer_id', $retailer_id)
->where('isConfirmed', 1)
->where('created_at', '<=', $search['created_end'])
->where('created_at', '>=', $search['created_start'])
->get_all();
if (!empty($orders)) {
foreach ($orders as $order){
$income['revenue'][] = [
'name' => '消費者訂購',
'totalQty' => $order['items'][0]['totalQty'],
'total' => $order['items'][0]['total'],
];
$income['totalQty'] += $order['items'][0]['totalQty'];
$income['total'] += $order['items'][0]['total'];
}
}
}
$this->load->model('product_model');
$products = $this->product_model->getCustomerProducts();
$data = [
'search' => $search,
'income' => $income,
'retailers' => $retailers,
'products' => $products,
'title' => '產品業績',
'view' => 'income/product',
];
$this->_preload($data);
}
}
?><file_sep>/application/libraries/Purchase_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Purchase_lib
{
var $CI;
var $purchase = [];
public function __construct($purchase=[])
{
$this->CI =& get_instance();
$this->purchase = $purchase;
$this->CI->load->model('purchase_model');
$this->CI->load->model('retailer_relationship_model');
$this->CI->load->helper('data_format');
}
//取得經銷商訂購紀錄
public function getRetailerTotalPurchases($retailer_id, $end_day = null)
{
$total = 0;
$count = 0;
$first_at = null;
$first_total = 0;
if (!is_null($end_day)){
$this->CI->purchase_model->where('created_at', '<', $end_day);
}
$first_purchase = $this->CI->purchase_model
->where('retailer_id', $retailer_id)
->where('isConfirmed', 1)
->order_by('created_at', 'asc')
->get();
if ($first_purchase){
$first_at = $first_purchase['created_at'];
$first_total = $first_purchase['subtotal'];
$table = $this->CI->purchase_model->get_table_name();
$purchase = $this->CI->purchase_model
->fields('SUM(' . $table . '.subtotal) as total, COUNT(' . $table . '.id) AS counted_rows')
->where('retailer_id', $retailer_id)
->where('isConfirmed', 1)
->get();
if ($purchase){
$total = $purchase['total'];
$count = $purchase['counted_rows'];
}
}
return [
'count' => $count,
'total' => $total,
'first_at' => $first_at,
'first_total' => $first_total,
];
}
//訂貨單確認
public function generateConfirmLabel($showMemo = false)
{
$string = '';
if (is_null($this->purchase['isConfirmed'])){
$string .= '<span class="badge badge-warning">待回覆</span>';
} else {
$confirm = isset($this->purchase['confirm']) ? $this->purchase['confirm'] : [];
if ($confirm) {
$string .= confirmStatus($confirm['audit'], $confirm['memo']);
if ($showMemo) {
$string .= '<div>' . nl2br($confirm['memo']) . '</div>';
}
}
}
return $string;
}
//收付款狀態
public function generatePaidLabel($showMemo = false)
{
$string = eventStatus($this->purchase['isPaid']);
if ($this->purchase['isPaid'] && !$this->purchase['isPayConfirmed']){
$string .= ' <span class="badge badge-warning">待確認</span>';
}
return $string;
}
//出貨狀態
public function generateShippedLabel()
{
$string = eventStatus($this->purchase['isShipped']);
if ($this->purchase['isShipped'] && !$this->purchase['isShipConfirmed']){
$string .= ' <span class="badge badge-warning">待確認</span>';
}
return $string;
}
public function getShipOutList($retailer_id)
{
$_retailers = $this->CI->retailer_relationship_model
->with_relation()
->where('relation_type', 'shipout')
->where('retailer_id', $retailer_id)
->get_all();
$retailers = [];
if ($_retailers){
foreach ($_retailers as $r){
$retailers[$r['relation_retailer_id']] = [
'id' => $r['relation_retailer_id'],
'company' => $r['relation']['company'],
'invoice_title' => $r['relation']['invoice_title'],
'discount' => $r['discount'],
'hasStock' => $r['relation']['hasStock'],
];
}
}
return $retailers;
}
public function getShipOutListReverse($retailer_id)
{
$_retailers = $this->CI->retailer_relationship_model
->with_retailer()
->where('relation_type', 'shipout')
->where('relation_retailer_id', $retailer_id)
->get_all();
$retailers = [];
if ($_retailers){
foreach ($_retailers as $r){
$retailers[$r['retailer_id']] = [
'id' => $r['retailer_id'],
'company' => $r['retailer']['company'],
'invoice_title' => $r['retailer']['invoice_title'],
];
}
}
return $retailers;
}
public function getShipInList($retailer_id, $shipout_retailer_id)
{
$_retailers = $this->CI->retailer_relationship_model
->with_alter()
->where('relation_type', 'shipin')
->where('retailer_id', $retailer_id)
->where('relation_retailer_id', $shipout_retailer_id)
->get_all();
$retailers = [];
if ($_retailers){
foreach ($_retailers as $r){
$data = [
'id' => $r['alter_retailer_id'],
'company' => $r['alter']['company'],
'invoice_title' => $r['alter']['invoice_title'],
'retailer_role_id' => $r['alter']['retailer_role_id'],
'address' => $r['alter']['address'],
'purchaseThreshold' => $r['alter']['purchaseThreshold'],
'hasStock' => $r['alter']['hasStock'],
'level' => [],
];
if (!empty($r['retailer_level_id'])) {
$retailer_level = $this->retailer_level_model->get($r['retailer_level_id']);
if ($retailer_level) {
$data['level'] = [
'firstThreshold' => $retailer_level['firstThreshold'],
'monthThreshold' => $retailer_level['monthThreshold'],
];
}
}
$retailers[$r['alter_retailer_id']] = $data;
}
}
return $retailers;
}
public function getInvoiceList($retailer_id, $shipout_retailer_id)
{
$_retailers = $this->CI->retailer_relationship_model
->with_alter()
->where('relation_type', 'invoice')
->where('retailer_id', $retailer_id)
->where('relation_retailer_id', $shipout_retailer_id)
->get_all();
$retailers = [];
if ($_retailers){
foreach ($_retailers as $r){
$retailers[$r['alter_retailer_id']] = [
'id' => $r['alter_retailer_id'],
'company' => $r['alter']['company'],
'invoice_title' => $r['alter']['invoice_title'],
'discount' => $r['discount'],
];
}
}
return $retailers;
}
public function getInvoiceSendList($retailer_id)
{
$_retailers = $this->CI->retailer_relationship_model
->with_relation()
->where('relation_type', 'invoice_send')
->where('retailer_id', $retailer_id)
->get_all();
$retailers = [];
if ($_retailers){
foreach ($_retailers as $r){
$retailers[$r['relation_retailer_id']] = [
'id' => $r['relation_retailer_id'],
'company' => $r['relation']['company'],
'invoice_title' => $r['relation']['invoice_title'],
'address' => $r['relation']['address'],
];
}
}
return $retailers;
}
//計算月份差
public function get_month_diff($start, $end = FALSE)
{
if (!$end) $end = date('Y-m-d');
$start_year = date('Y', strtotime($start));
$start_month = date('m', strtotime($start));
$end_year = date('Y', strtotime($end));
$end_month = date('m', strtotime($end));
if ($end_month < $start_month){
$end_year--;
$end_month += 12;
}
return ($end_year - $start_year) * 12 + $end_month - $start_month;
}
}
?><file_sep>/application/views/capital/promote/method/add.php
<div class="container">
<h1 class="mb-4"><?= $promote['title'] ?>優惠方式設定</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">優惠方式</label>
<?php
echo form_dropdown('promote_type_id', ['' => ''] + $promote_type, '', 'id="promote_type_id" class="form-control" required');
?>
</div>
</form>
</div>
<script>
$().ready(function () {
$('#promote_type_id').change(function () {
var promote_type_id = parseInt($(this).val()) || 0;
if (promote_type_id > 0) {
window.location = '<?=base_url('capital_promote_method/add/' . $promote['id'] . '/') ?>' + promote_type_id;
}
});
});
</script><file_sep>/application/views/consumer/index.php
<div class="container">
<div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
<?php if (!empty($authority['customer'])){ ?>
<a href="<?=base_url('/customer/overview')?>" class="btn btn-success mr-4">個人歷史消費紀錄</a>
<?php } ?>
<?php if (!empty($authority['consumer'])){ ?>
<a href="<?=base_url('/consumer/overview')?>" class="btn btn-success mr-4">銷售單位歷史銷售</a>
<?php } ?>
<?php if (!empty($authority['coupon'])){ ?>
<a href="<?=base_url('/coupon/overview')?>" class="btn btn-success">貴賓優惠券序號登錄</a>
<?php } ?>
</div>
</div><file_sep>/application/views/consumer/transfer.php
<div class="container">
<h1 class="mb-4">A店買B店取貨之紀錄</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">日期</th>
<th class="text-center">取貨人</th>
<th class="text-center">電話</th>
<th class="text-center">售出單位</th>
<th class="text-center">取貨單位</th>
<th class="text-center">新增進貨單</th>
<th class="text-center">開立取貨單</th>
<th class="text-center">是否取貨</th>
<th class="text-center"></th>
</tr>
<?php
if ($transfers) {
foreach ($transfers as $transfer) {
?>
<tr>
<td class="text-center"><?= date('Y-m-d', strtotime($transfer['created_at'])) ?></td>
<td class="text-center"><?= !empty($transfer['order']['contact']['name']) ? $transfer['order']['contact']['name'] : '' ?></td>
<td class="text-center"><?= !empty($transfer['order']['contact']['phone']) ? $transfer['order']['contact']['phone'] : '' ?></td>
<td class="text-center"><?= $transfer['retailer']['company'] ?></td>
<td class="text-center"><?= $transfer['shipout_retailer']['company'] ?></td>
<td class="text-center"><?= yesno($transfer['purchase_id']) ?></td>
<td class="text-center"><?= yesno($transfer['isRecorded']) ?></td>
<td class="text-center"><?= yesno($transfer['isDeliveried']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if ($transfer['retailer_id'] == $dealer['retailer_id'] && !$transfer['isRecorded'] && !empty($authority['transfer_record'])){ ?>
<a class="btn btn-warning btn-sm" href="<?= base_url('/consumer/transfer_record/' . $transfer['id']) ?>">
已開立取貨單
</a>
<?php } ?>
<?php if ($transfer['shipout_retailer_id'] == $dealer['retailer_id'] && $transfer['isRecorded'] && !$transfer['isDeliveried'] && !empty($authority['transfer_delivery'])){ ?>
<a class="btn btn-warning btn-sm" href="<?= base_url('/consumer/transfer_delivery/' . $transfer['id']) ?>">
確認取貨
</a>
<?php } ?>
<?php if (!empty($authority['detail'])){ ?>
<a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $transfer['order_id']) ?>">
<i class="fas fa-search"></i> 明細
</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="9" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/migrations/008_add_payment.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_payment extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'pay_type' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => TRUE,
],
'pay_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'paid_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'received_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'price' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'receipt' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'isConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_payments');
}
public function down()
{
$this->dbforge->drop_table('olive_payments');
}
}<file_sep>/application/controllers/Capital_combo.php
<?php
class Capital_combo extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('combo_model');
$this->load->model('combo_item_model');
$this->session->set_userdata('return_page', base_url('/capital_combo/overview'));
}
public function overview()
{
$total_combos_count = $this->combo_model
->count_rows();
$combos = $this->combo_model
->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
->order_by('id', 'desc')
->paginate(20, $total_combos_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_combo', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_combo', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_combo', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'combos' => $combos,
'pagination' => $this->combo_model->all_pages,
'authority' => $authority,
'title' => '商品組合列表',
'view' => 'capital/combo/overview',
];
$this->_preload($data);
}
public function add()
{
$this->load->model('product_model');
$products = $this->product_model->getCustomerProducts();
if ($this->input->post()) {
$this->form_validation->set_rules('name', '組合名稱', 'required|max_length[100]');
$this->form_validation->set_rules('items[][price]', '產品金額', 'callback_check_total[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');
if ($this->form_validation->run() !== FALSE) {
$combo_id = $this->combo_model->insert([
'name' => $this->input->post('name'),
]);
$items = (array)$this->input->post('items');
$total = 0;
foreach ($items as $product_id => $item) {
$this->combo_item_model->insert([
'combo_id' => $combo_id,
'product_id' => $product_id,
'price' => $item['price'],
'qty' => $item['qty'],
]);
$total += $item['price'] * $item['qty'];
}
$this->combo_model->update([
'total' => $total,
], ['id' => $combo_id]);
redirect(base_url('/capital_combo/overview/'));
}
}
$this->load->helper('form');
$data = [
'products' => $products,
'title' => '新增商品組合',
'view' => 'capital/combo/add',
];
$this->_preload($data);
}
public function edit($combo_id)
{
$combo = $this->combo_model
->with_items()
->get($combo_id);
if (!$combo_id || !$combo) {
show_error('查無商品組合資料');
}
$this->load->model('product_model');
$products = $this->product_model->getCustomerProducts();
if ($this->input->post()) {
$this->form_validation->set_rules('name', '組合名稱', 'required|max_length[100]');
$this->form_validation->set_rules('items[][price]', '產品金額', 'callback_check_total[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');
if ($this->form_validation->run() !== FALSE) {
$this->combo_model->update([
'name' => $this->input->post('name'),
], ['id' => $combo_id]);
$this->combo_item_model->where('combo_id', $combo_id)->delete();
$items = (array)$this->input->post('items');
$total = 0;
foreach ($items as $product_id => $item) {
$this->combo_item_model->insert([
'combo_id' => $combo_id,
'product_id' => $product_id,
'price' => $item['price'],
'qty' => $item['qty'],
]);
$total += $item['price'] * $item['qty'];
}
$this->combo_model->update([
'total' => $total,
], ['id' => $combo_id]);
redirect(base_url('/capital_combo/overview/'));
}
}
$_items = $combo['items'];
$items = [];
foreach ($_items as $item){
$items[$item['product_id']] = $item;
}
$data = [
'products' => $products,
'combo' => $combo,
'items' => $items,
'title' => '編輯商品組合',
'view' => 'capital/combo/edit',
];
$this->_preload($data);
}
public function check_total($i, $params)
{
$params = json_decode($params, true);
$products = $params['products'];
$items = $params['items'];
$totalQty = 0;
$error = '';
foreach ($items as $product_id => $item) {
if (!isset($products[$product_id])) {
$error = '輸入的貨品有誤';
break;
}
if ((!$item['price'] && $item['price'] !== '0') || !$item['qty']) {
$error = '數量與組合分攤單價必須填寫';
break;
}
$totalQty += $item['qty'];
}
if ($totalQty < 2){
$error = '商品組合至少要有兩樣產品';
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_total', $error);
return false;
}
}
public function cancel($combo_id)
{
$combo = $this->combo_model
->get($combo_id);
if (!$combo_id || !$combo) {
show_error('查無商品組合資料');
}
$this->combo_model->delete($combo_id);
redirect(base_url('/capital_combo/overview/'));
}
}
?><file_sep>/application/migrations/016_add_recommend.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_recommend extends CI_Migration
{
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'type' => [
'type' => 'CHAR',
'constraint' => 1,
'default' => 'I'
],
'content' => [
'type' => 'text'
],
'isConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_recommend_templates');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'recommend_template_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'picture1' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'picture2' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'picture3' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'isTemp' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_recommends');
}
public function down()
{
$this->dbforge->drop_table('olive_recommend_templates');
$this->dbforge->drop_table('olive_recommends');
}
}<file_sep>/application/models/Free_package_item_model.php
<?php
class Free_package_item_model extends MY_Model
{
public $table = 'olive_free_package_items';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
}
}
?>
<file_sep>/application/libraries/Customer_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Customer_lib
{
var $CI;
var $customer_id = '';
var $customer = [];
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->model('customer_model');
$this->CI->load->model('customer_level_model');
$this->CI->load->model('order_model');
$this->CI->load->model('customer_level_history_model');
}
public function setCustomerID($customer_id)
{
$this->customer_id = $customer_id;
$this->setCustomer();
}
public function setCustomer()
{
$this->customer = $this->CI->customer_model
->with_level()
->get($this->customer_id);
}
public function getCustomer()
{
return $this->customer;
}
public function getCustomerLevels()
{
return $this->CI->customer_level_model->get_all();
}
public function downgradeCheckByPhone($phone)
{
$customers = $this->CI->customer_model
->with_level()
->where('phone', $phone)
->get_all();
if ($customers) {
foreach ($customers as $customer) {
$this->customer_id = $customer['id'];
$this->customer = $customer;
$this->downgradeCheckCustomerLevel();
}
}
}
//檢查降級狀態
public function downgradeCheckCustomerLevel()
{
$isChange = false;
if ($this->customer && !$this->customer['isDealer']) {
if (!is_null($this->customer['old_customer_id'])) { //舊會員才會降級
if ($this->customer['customer_level_id'] == 2) {
$count = $this->getCountOrderOfYear(1);
$total = $this->getLargestPriceOrderOfYear();
if ($count > 0 && $count < 12 && $total < 12000) {
$this->CI->customer_model->update([
'customer_level_id' => 1,
], ['id' => $this->customer_id]);
$this->saveLevelChangeHistory(1, 1);
$isChange = true;
}
}
$count = $this->getCountOrderOfYear(2);
if (!$count) {
$this->CI->customer_model->update([
'customer_level_id' => null,
], ['id' => $this->customer_id]);
$this->saveLevelChangeHistory(null, 1);
$isChange = true;
}
}
}
//重新整理
if ($isChange) {
$this->setCustomer();
}
return;
}
protected function getCountOrderOfYear($year = 1)
{
$firstTime = $this->customFirstTime();
if ($firstTime) {
$check_start_date = date("Y-m-d", strtotime($firstTime['created_at']));
$check_end_date = date("Y-m-d", strtotime($check_start_date . " + " . $year . " year"));
return $this->CI->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer['id'])
->where('created_at', '>=', $check_start_date)
->where('created_at', '<', $check_end_date)
->count_rows();
}
return true;
}
protected function getLargestPriceOrderOfYear()
{
$firstTime = $this->customFirstTime();
if ($firstTime) {
$check_start_date = date("Y-m-d", strtotime($firstTime['created_at']));
$check_end_date = date("Y-m-d", strtotime($check_start_date . " + 1 year"));
return $this->CI->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer['id'])
->where('created_at', '>=', $check_start_date)
->where('created_at', '<', $check_end_date)
->order_by('total', 'desc')
->get();
}
return true;
}
//升級規則
public function upgradeLevel()
{
if (!$this->customer || $this->customer['isDealer']) return false;
if (empty($this->customer['customer_level_id'])) {
$customer_level_id = null;
} else {
$customer_level_id = intval($this->customer['customer_level_id']);
}
$level = false;
switch ($customer_level_id) {
case 1:
$level = $this->upgradeLevel2Rule();
break;
case 2:
$level = $this->upgradeLevel3Rule();
break;
case 3:
break;
default:
$level = $this->upgradeLevel1Rule();
break;
}
return $level;
}
//消費者第一次購買日期
protected function customFirstTime()
{
$order_data = $this->CI->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer_id)
->where('isConfirmed', 1)
->where('isPaid', 1)
->where('isShipped', 1)
->order_by('created_at', 'asc')
->get();
if ($order_data) {
return $order_data;
}
return false;
}
protected function upgradeLevel1Rule()
{
$rule = [
'once' => 12000,
'year' => 20000,
];
$level = false;
$accountYearRange = $this->getAccountYearRange();
$orders = $this->CI->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer_id)
->where('created_at', '>=', $accountYearRange['start'])
->where('created_at', '<=', $accountYearRange['end'])
->order_by('total', 'desc')
->get();
if ($orders && $orders['total'] >= $rule['once']) {
$level = 1;
}
if (!$level) {
$table = $this->CI->order_model->get_table_name();
$orders = $this->CI->order_model
->fields('SUM(' . $table . '.total) as total')
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer_id)
->where('created_at', '>=', $accountYearRange['start'])
->where('created_at', '<=', $accountYearRange['end'])
->get();
if ($orders && $orders['total'] >= $rule['year']) {
$level = 1;
}
}
return $level;
}
protected function upgradeLevel2Rule()
{
$rule = [
'count' => 6,
];
$level = false;
$accountYearRange = $this->getAccountYearRange();
//本年度消費次數
$total_orders_count = $this->CI->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer_id)
->where('created_at', '>=', $accountYearRange['start'])
->where('created_at', '<=', $accountYearRange['end'])
->count_rows();
if ($total_orders_count >= $rule['count']) {
$level = 2;
}
return $level;
}
protected function upgradeLevel3Rule()
{
$rule = [
'count' => 20,
'year' => 330000,
];
$level = false;
$accountYearRange = $this->getAccountYearRange();
//本年度消費次數
$total_orders_count = $this->CI->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer_id)
->where('created_at', '>=', $accountYearRange['start'])
->where('created_at', '<=', $accountYearRange['end'])
->count_rows();
if ($total_orders_count >= $rule['count']) {
//本年度消費總額
$table = $this->CI->order_model->get_table_name();
$orders = $this->CI->order_model
->fields('SUM(' . $table . '.total) as total')
->where('buyer_type', 'customer')
->where('buyer_id', $this->customer_id)
->where('created_at', '>=', $accountYearRange['start'])
->where('created_at', '<=', $accountYearRange['end'])
->get();
if ($orders && $orders['total'] >= $rule['year']) {
$level = 3;
}
}
return $level;
}
public function saveLevelChangeHistory($customer_level_id, $isConfirmed = false)
{
if (!$this->customer || $this->customer['isDealer']) return false;
$this->CI->customer_level_history_model->insert([
'customer_id' => $this->customer['id'],
'old_customer_level_id' => empty($this->customer['customer_level_id']) ? null : $this->customer['customer_level_id'],
'new_customer_level_id' => $customer_level_id,
'isConfirmed' => $isConfirmed,
]);
}
//年度的計算時間改為 “每年8月1日至次年7月31日”為一年度
public function getAccountYearRange()
{
$y = date('Y');
$m = date('m');
if ($m < 8){
return [
'start' => ($y-1) . '-8-1',
'end' => $y . '-7-31',
];
} else {
return [
'start' => $y . '-8-1',
'end' => ($y+1) . '-7-31',
];
}
}
public function getCurrentSeasonRange()
{
$time = time();
$year = date('Y', $time);
$month = date('m', $time);
if ($month < 4){
return [
$year . '-01-01',
$year . '-03-31',
];
} elseif ($month < 7){
return [
$year . '-04-01',
$year . '-06-30',
];
} elseif ($month < 10){
return [
$year . '-07-01',
$year . '-09-30',
];
} else {
return [
$year . '-10-01',
$year . '-12-31',
];
}
}
}
?><file_sep>/application/views/payment/confirm.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">確認收款作業</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">付款金額</label>
<div>$<?=number_format($payment['price'])?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">付款單位</label>
<div><?=$payment['paid_retailer']['company']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">收款單位</label>
<div><?=$payment['received_retailer']['company']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">付款方式</label>
<div><?= paymentType($payment['type_id']) ?></div>
</div>
<?php if ($payment['receipt']){ ?>
<div class="form-group">
<label class="font-weight-bold">付款憑證</label>
<div><img class="img-fluid" src="<?=$payment['receipt']?>" /></div>
</div>
<?php } ?>
<div class="form-group text-center">
<input type="submit" name="refused" class="btn btn-danger" value="尚未收款"/>
<input type="submit" name="confirmed" class="btn btn-success" value="收款無誤"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/capital/retailer/qualification/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">更新<?= $retailer['company'] ?>經銷拓展資格</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>類別</label>
<input name="type" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
</div>
<div class="form-group">
<label>代碼</label>
<input name="code" class="form-control-plaintext" value="<?= $level['code'] ?>" />
</div>
<div class="form-group">
<label>名稱</label>
<input name="title" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">經銷拓展資格</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="qualification" id="yesno_1" value="1" required<?php if ($qualification){ echo ' checked';} ?>>
<label class="form-check-label" for="yesno_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="qualification" id="yesno_0" value="0"<?php if (!$qualification){ echo ' checked';} ?>>
<label class="form-check-label" for="yesno_0">否</label>
</div>
</div>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_retailer_qualification/overview/' . $retailer['id'])?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/consumer/overview.php
<div class="container">
<h1 class="mb-4">
<?= $dealer['company'] ?>歷史銷售紀錄
<div class="float-right">
<?php if (!empty($authority['trashed'])){ ?>
<a href="<?=base_url('/consumer/trashed/') ?>" class="btn btn-warning">取消之消費紀錄</a>
<?php } ?>
</div>
</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">編號</th>
<th class="text-center">日期</th>
<th class="text-center">姓名</th>
<th class="text-center">電話</th>
<th class="text-center">總額</th>
<th class="text-center"></th>
</tr>
<?php
if ($orders) {
$amount = 0;
foreach ($orders as $order) {
$amount += $order['total'];
?>
<tr>
<td class="text-center"><?= $order['orderNum'] ?></td>
<td class="text-center"><?= date('Y-m-d', strtotime($order['created_at'])) ?></td>
<td class="text-center">
<?php if (!empty($authority['customer']) && $order['buyer_id']) { ?>
<a href="<?= base_url('/customer/consumer/' . $order['buyer_id']) ?>"><?= $order['contact']['name'] ?></a>
<?php } ?>
</td>
<td class="text-center">
<?php if ($order['buyer_id']) { ?>
<?= $order['contact']['phone'] ?>
<?php } ?>
</td>
<td class="text-right">$<?= number_format($order['total']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['detail'])){ ?>
<a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $order['id']) ?>">
<i class="fas fa-search"></i> 明細
</a>
<?php } ?>
<?php
if ($order['shipout_retailer_id'] == $dealer['retailer_id']) { ?>
<button type="button" class="btn btn-info btn-sm dropdown-toggle dropdown-toggle-split"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<?php if (!empty($authority['edit'])){ ?>
<a class="dropdown-item" href="<?= base_url('/consumer/edit/' . $order['id']) ?>">編輯消費紀錄</a>
<?php } ?>
<?php if (!empty($authority['cancel'])){ ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"
data-href="<?= base_url('/consumer/cancel/' . $order['id']) ?>"
data-toggle="modal" data-target="#confirm-delete"><i class="fas fa-trash"></i>
取消消費紀錄</a>
<?php } ?>
</div>
<?php } ?>
</div>
</td>
</tr>
<?php
}
?>
<tr>
<th colspan="4" class="text-right">累計消費金額</th>
<td class="text-right">
$<?= number_format($amount) ?>
</td>
<td></td>
</tr>
<?php
} else {
?>
<tr>
<td colspan="6" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal" id="confirm-delete" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-trash"></i> 刪除確認</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>是否確定刪除?</p>
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
<a href="" class="btn btn-danger btn-confirm"><i class="fas fa-trash"></i> 刪除</a>
</div>
</div>
</div>
</div>
<script>
$().ready(function () {
$('#confirm-delete').on('show.bs.modal', function (e) {
$(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
});
});
</script><file_sep>/application/views/commission/dealer.php
<div class="container">
<h1 class="mb-4"><?= $dealer['name'] ?> 輔銷人獎金</h1>
<h4>輔銷獎金總計 $<?=number_format($total_commission)?></h4>
<h4><?= $commissionMonth ?>輔銷獎金合計 $<?=number_format($month_total_commission)?></h4>
<?php
if ($retailers) {
foreach ($retailers as $retailer_id => $r) {
if ($r['commissions']) {
?>
<div class="my-4">
<h4 class="mb-2"><?= $r['company'] ?>經銷商(輔銷單位: <?= $r['sales_retailer']['company'] ?>,
輔銷人: <?= $r['sales_dealer']['name'] ?>)</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">進貨單編號</th>
<th class="text-center">進貨日期</th>
<th class="text-center">金額</th>
<th class="text-center">獎金</th>
</tr>
<?php
foreach ($r['commissions'] as $commission) {
?>
<tr>
<td class="text-center"><?= $commission['purchase']['purchaseNum'] ?></td>
<td class="text-center"><?= $commission['created_at'] ?></td>
<td class="text-right">$<?= number_format($commission['purchase']['total']) ?></td>
<td class="text-right">$<?= number_format($commission['total']) ?></td>
</tr>
<?php
}
?>
<tr>
<th class="text-right" colspan="3">獎金小計</th>
<td class="text-right">$<?= number_format($r['subtotal']) ?></td>
</tr>
</table>
</div>
<?php
}
}
}
?>
<div class="text-center my-4">
<?php if ($prevMonthUrl){ ?>
<a href="<?=$prevMonthUrl?>" class="btn btn-success mr-2">前一個月</a>
<?php } ?>
<?php if ($nextMonthUrl){ ?>
<a href="<?=$nextMonthUrl?>" class="btn btn-success">後一個月</a>
<?php } ?>
</div>
</div><file_sep>/application/controllers/Stock.php
<?php
class Stock extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || !$this->dealer['hasStock']) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('stock_model');
$this->load->model('product_model');
$this->session->set_userdata('return_page', base_url('/stock/overview'));
}
public function overview()
{
$retailer_id = $this->dealer['retailer_id'];
$retailer = $this->retailer_model
->get($retailer_id);
$products = $this->product_model->getUnitProductStocks($retailer_id);
//權限設定
$authority = array();
if ($this->authentic->authority('stock', 'detail')){
$authority['detail'] = true;
}
$data = [
'retailer' => $retailer,
'products' => $products,
'authority' => $authority,
'title' => '庫存列表',
'view' => 'stock/overview',
];
$this->_preload($data);
}
public function detail($product_id)
{
$retailer_id = $this->dealer['retailer_id'];
$product = $this->product_model
->with_pao()
->where('pKind', [3,6])
->where('pEnable', 'Y')
->where('pdId', $product_id)
->get();
if (!$product_id || !$product) {
show_error('查無經銷單位商品資料!');
}
$retailer = $this->retailer_model
->get($retailer_id);
$stocks = $this->stock_model
->where('product_id', $product['pdId'])
->where('retailer_id', $retailer_id)
->where('stock', '>', 0)
->order_by('expired_at', 'asc')
->get_all();
$product['stock'] = $this->product_model->calcStock($stocks, $product);
$data = [
'retailer' => $retailer,
'product' => $product,
'title' => '詳細產品庫存資訊',
'view' => 'stock/detail',
];
$this->_preload($data);
}
}
?><file_sep>/application/controllers/Capital_free_package.php
<?php
class Capital_free_package extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('free_package_item_model');
$this->session->set_userdata('return_page', base_url('/capital_free_package/overview'));
}
public function overview()
{
$total_free_packages_count = $this->free_package_item_model
->count_rows();
$free_packages = $this->free_package_item_model
->with_product()
->order_by('id', 'desc')
->paginate(20, $total_free_packages_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_free_package', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_free_package', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'free_packages' => $free_packages,
'pagination' => $this->free_package_item_model->all_pages,
'authority' => $authority,
'title' => '免費包裝列表',
'view' => 'capital/free_package/overview',
];
$this->_preload($data);
}
public function add()
{
$this->load->model('product_model');
$products = $this->product_model->getPackageProducts();
if ($this->input->post()) {
$this->form_validation->set_rules('product_id', '包裝產品', 'required|integer|in_list[' . implode(',',array_keys($products)) . ']|callback_check_duplicate');
if ($this->form_validation->run() !== FALSE) {
$this->free_package_item_model->insert([
'product_id' => $this->input->post('product_id'),
]);
redirect(base_url('/capital_free_package/overview/'));
}
}
$data = [
'products' => $products,
'title' => '新增免費包裝',
'view' => 'capital/free_package/add',
];
$this->_preload($data);
}
public function check_duplicate($product_id){
$results = $this->free_package_item_model
->where('product_id', $product_id)
->get_all();
if (!$results) {
return true;
} else {
$this->form_validation->set_message('check_duplicate', '此包裝已經建立,請勿重複新增');
return false;
}
}
public function cancel($id)
{
$free_package = $this->free_package_item_model
->get($id);
if (!$id || !$free_package) {
show_error('查無免費包裝資料');
}
$this->free_package_item_model->delete($id);
redirect(base_url('/capital_free_package/overview/'));
}
}
?><file_sep>/application/views/customer/old_detail.php
<div class="container">
<h1 class="mb-4">舊有會員全部匯入資訊</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">會員代號</th>
<td><?=$customer['customerNum']?></td>
</tr>
<tr>
<th class="text-center">會員名稱</th>
<td><?=$customer['name']?></td>
</tr>
<tr>
<th class="text-center">有效起始日</th>
<td><?=$customer['valid_at']?></td>
</tr>
<tr>
<th class="text-center">有效到期日</th>
<td><?=$customer['expired_at']?></td>
</tr>
<tr>
<th class="text-center">性別</th>
<td><?=gender($customer['gender'])?></td>
</tr>
<tr>
<th class="text-center">行動電話</th>
<td><?=$customer['phone']?></td>
</tr>
<tr>
<th class="text-center">地址</th>
<td><?=$customer['address']?></td>
</tr>
<tr>
<th class="text-center">Email</th>
<td><?=$customer['email']?></td>
</tr>
<tr>
<th class="text-center">會員卡別</th>
<td><?=$customer['isVIP'] ? 'VIP' : ''?></td>
</tr>
<tr>
<th class="text-center">消費總金額</th>
<td>$<?=number_format($customer['amount'])?></td>
</tr>
<tr>
<th class="text-center">購買總次數</th>
<td><?=$customer['buytimes']?></td>
</tr>
</table>
</div><file_sep>/application/config/class_list.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config = array(
'capital_dealer' => array(
'alias' => '系統參數-單位人員管理',
'method' => array(
'overview' => '單位人員總覽',
'add' => '新增單位人員',
'edit' => '編輯單位人員',
'cancel' => '刪除單位人員',
),
),
'capital_level' => array(
'alias' => '系統參數-經銷規則管理',
'method' => array(
'overview' => '經銷規則總覽',
'add' => '新增經銷規則',
'edit' => '編輯經銷規則',
'cancel' => '刪除經銷規則',
),
),
'capital_level_type' => array(
'alias' => '系統參數-經銷類別管理',
'method' => array(
'overview' => '經銷類別總覽',
'edit' => '編輯經銷類別',
),
),
'capital_customer_level' => array(
'alias' => '系統參數-會員資格管理',
'method' => array(
'overview' => '會員資格總覽',
'edit' => '編輯會員資格',
),
),
'capital_privilege' => array(
'alias' => '系統參數-經銷類別管理',
'method' => array(
'overview' => '權限總覽',
'apps' => '頁面權限總覽',
'authority' => '動作權限設定',
),
),
'capital_relationship_invoice' => array(
'alias' => '系統參數-發票關係單位管理',
'method' => array(
'overview' => '發票關係單位總覽',
'add' => '新增發票關係單位',
'edit' => '編輯發票關係單位',
'cancel' => '刪除發票關係單位',
),
),
'capital_relationship_invoice_send' => array(
'alias' => '系統參數-發票寄送關係單位管理',
'method' => array(
'overview' => '發票寄送關係單位總覽',
'add' => '新增發票寄送關係單位',
'cancel' => '刪除發票寄送關係單位',
),
),
'capital_relationship_shipin' => array(
'alias' => '系統參數-收貨關係單位管理',
'method' => array(
'overview' => '收貨關係單位總覽',
'add' => '新增收貨關係單位',
'cancel' => '刪除收貨關係單位',
),
),
'capital_relationship_shipout' => array(
'alias' => '系統參數-出貨關係單位管理',
'method' => array(
'overview' => '出貨關係單位總覽',
'add' => '新增出貨關係單位',
'edit' => '編輯出貨關係單位',
'cancel' => '刪除出貨關係單位',
),
),
'capital_relationship_visor' => array(
'alias' => '系統參數-輔銷關係單位管理',
'method' => array(
'overview' => '輔銷關係單位總覽',
'add' => '新增輔銷關係單位',
'cancel' => '刪除輔銷關係單位',
),
),
'capital_retailer' => array(
'alias' => '系統參數-單位管理',
'method' => array(
'overview' => '單位總覽',
'add' => '新增單位',
'edit' => '編輯單位',
'cancel' => '刪除單位',
),
),
'capital_retailer_group' => array(
'alias' => '系統參數-群組管理',
'method' => array(
'overview' => '群組總覽',
'add' => '新增群組',
'edit' => '編輯群組',
),
),
'capital_retailer_role' => array(
'alias' => '系統參數-單位類型管理',
'method' => array(
'overview' => '單位類型總覽',
),
),
'capital_retailer_qualification' => array(
'alias' => '系統參數-經銷拓展資格',
'method' => array(
'overview' => '經銷拓展資格總覽',
'edit' => '編輯經銷拓展資格',
),
),
'capital_pao' => array(
'alias' => '系統參數-商品期限參數',
'method' => array(
'overview' => '商品期限參數總覽',
'add' => '新增商品期限參數',
'edit' => '編輯商品期限參數',
'cancel' => '刪除商品期限參數',
),
),
'capital_product' => array(
'alias' => '系統參數-商品管理',
'method' => array(
'overview' => '商品總覽',
'add' => '新增商品',
'edit' => '編輯商品',
'cancel' => '刪除商品',
),
),
'capital_product_permission' => array(
'alias' => '系統參數-進貨商品管理',
'method' => array(
'overview' => '進貨商品總覽',
'edit' => '編輯進貨商品',
),
),
'capital_product_relationship' => array(
'alias' => '系統參數-出貨單位產品折扣',
'method' => array(
'edit' => '編輯出貨單位產品折扣',
),
),
'capital_combo' => array(
'alias' => '系統參數-商品組合管理',
'method' => array(
'overview' => '商品組合總覽',
'add' => '新增商品組合',
'edit' => '編輯商品組合',
'cancel' => '刪除商品組合',
'check_total' => '檢查商品、數量是否正確',
),
),
'capital_free_package' => array(
'alias' => '系統參數-免費包裝管理',
'method' => array(
'overview' => '免費包裝總覽',
'add' => '新增免費包裝',
'cancel' => '刪除免費包裝',
'check_duplicate' => '檢查是否有重複新增免費包裝商品',
),
),
'capital_promote' => array(
'alias' => '系統參數-優惠活動管理',
'method' => array(
'overview' => '優惠活動總覽',
'add' => '新增優惠活動',
'edit' => '編輯優惠活動',
'cancel' => '刪除優惠活動',
),
),
'capital_promote_method' => array(
'alias' => '系統參數-優惠方式管理',
'method' => array(
'overview' => '優惠方式總覽',
'add' => '新增優惠方式',
'edit' => '編輯優惠方式',
'cancel' => '刪除優惠方式',
),
),
'capital_option' => array(
'alias' => '系統參數-其他',
'method' => array(
'customer' => '編輯消費者參數',
),
),
'capital_stock' => array(
'alias' => '單位庫存',
'method' => array(
'overview' => '單位庫存總覽',
'detail' => '詳細產品庫存資訊',
),
),
'stock' => array(
'alias' => '該單位庫存',
'method' => array(
'overview' => '該單位庫存總覽',
'detail' => '詳細產品庫存資訊',
),
),
'stock_counting' => array(
'alias' => '盤點作業',
'method' => array(
'index' => '盤點作業首頁選單',
'overview' => '盤點歷史紀錄列表',
'detail' => '盤盈虧報表',
'set_print' => '盤點清冊下載',
'process_print' => '盤點清冊列印',
'add' => '盤盈虧報表新增',
'edit' => '盤盈虧報表編輯',
),
),
'guest' => array(
'alias' => '經銷商首次訂購',
'method' => array(
'level' => '經銷商身份類別選擇',
'cart' => '經銷商訂貨表單',
'check_total' => '檢查商品、數量、庫存、門檻是否正確',
'adminCheck' => '總監登入確認',
'check_authentic' => '總監登入帳號驗證',
'info' => '經銷商基本資料表單',
),
),
'purchase' => array(
'alias' => '進貨單管理',
'method' => array(
'overview' => '進貨單列表',
'detail' => '進貨單詳細資料',
'detail2' => '進貨單詳細資料(無金額)',
'add' => '新增進貨單',
'add2' => '新增進貨單(無金額)',
'check_total' => '檢查商品、數量、庫存、門檻是否正確',
'edit' => '編輯進貨單',
'cancel' => '取消進貨單',
),
),
'transfer' => array(
'alias' => '出貨單管理',
'method' => array(
'overview' => '出貨單列表',
'transfer' => '向上轉單動作',
'detail' => '出貨單詳細資料',
'detail2' => '出貨單詳細資料(無金額)',
'confirm' => '確認出貨單動作',
),
),
'payment' => array(
'alias' => '付款管理',
'method' => array(
'overview' => '付款紀錄列表',
'add' => '新增付款紀錄',
'confirms' => '待確認收款列表',
'confirm' => '確認付款動作',
'cancel' => '取消付款紀錄',
'purchase' => '進貨單位付款紀錄轉址',
),
),
'shipment' => array(
'alias' => '銷貨紀錄管理',
'method' => array(
'overview' => '銷貨紀錄列表',
'detail' => '銷貨紀錄列表',
'add' => '新增銷貨紀錄',
'check_shipping_qty' => '檢查新增銷貨商品、數量、庫存是否正確',
'confirm' => '確認銷貨',
'check_qty' => '檢查確認銷貨商品、數量是否正確',
'cancel' => '取消銷貨紀錄',
'revise_edit' => '編輯銷貨異動',
'confirm_revise' => '確認銷貨異動',
'return_add' => '新增銷貨退回',
'check_return_qty' => '檢查新增銷貨退回商品、數量是否正確',
'confirm_return' => '確認銷貨退回',
'allowance_add' => '新增銷貨折讓',
),
),
'commission' => array(
'alias' => '獎金',
'method' => array(
'dealers' => '輔銷人名單',
'dealer' => '輔銷人獎金',
),
),
'confirm' => array(
'alias' => '確認紀錄',
'method' => array(
'overview' => '確認紀錄列表',
),
),
'income' => array(
'alias' => '財務管理',
'method' => array(
'overview' => '營業資訊',
'product' => '商品業績',
),
),
'customer' => array(
'alias' => '消費者管理',
'method' => array(
'overview' => '消費者搜尋',
'edit' => '編輯消費者',
'consumer' => '該消費者歷史消費記錄',
'upgrade' => '符合飄雪白卡資格升級動作',
'old' => '未轉換舊有會員資訊',
'old_detail' => '舊有會員全部匯入資訊',
'conv_old' => '舊有會員轉換表單',
'active_old' => '會員資料區',
'import' => '匯入舊有會員資訊',
'export' => '匯出會員資訊',
),
),
'consumer' => array(
'alias' => '消費者消費管理',
'method' => array(
'index' => '消費紀錄選單',
'overview' => '銷售單位歷史銷售',
'detail' => '消費者消費明細',
'add' => '新增消費紀錄',
'check_qty' => '檢查商品、數量、庫存是否正確',
'check_promote' => '檢查優惠活動選擇是否正確',
'check_coupon' => '檢查核發優惠券是否重複',
'edit' => '編輯消費紀錄',
'cancel' => '刪除消費紀錄',
'old' => '舊有會員轉換',
'check_oldphone' => '檢查舊有會員是否已轉換',
'trashed' => '取消之消費紀錄',
'recover' => '恢復取消的消費紀錄',
'payAtShipped' => '貨到付款管理',
'shipping' => '貨到付款確認寄出',
'paying' => '貨到付款收款作業',
'reject' => '貨到付款客戶拒收',
'orderReturn' => '貨到付款退貨作業',
'transfer' => 'A店買B店取貨之紀錄',
'transfer_record' => 'A店買B店取貨開立取貨單',
'transfer_delivery' => 'A店買B店取貨確認取貨',
),
),
'coupon' => array(
'alias' => '折價券管理',
'method' => array(
'overview' => '折價券核發紀錄',
'edit' => '貴賓優惠券序號登錄',
),
),
'recommend' => array(
'alias' => '行銷作業管理',
'method' => array(
'overview' => '行銷作業區',
'temp' => '暫存作業區',
'add' => '來賓推薦作業',
'print_recommend' => '來賓推薦作業列印',
'edit' => '修改行銷作業',
),
),
'recommend_template' => array(
'alias' => '推薦函管理',
'method' => array(
'index' => '推薦函之增修',
'confirm' => '檢視或修改定案之推薦函',
'confirm_edit' => '修改定案之推薦函',
'inside' => '檢視或修改內部撰寫之推薦函',
'inside_add' => '新增內部撰寫之推薦函',
'inside_edit' => '修改定案之推薦函',
'outside' => '檢視或修改外部撰寫之推薦函',
'outside_add' => '新增外部撰寫之推薦函',
'outside_edit' => '修改外部撰寫之推薦函',
'confirming' => '內部、外部撰寫之推薦函定案動作',
),
),
'dealer' => array(
'alias' => '個人資料管理',
'method' => array(
'edit' => '單位資料修改',
'profile' => '個人資料修改',
'password' => '<PASSWORD>',
'check_password' => '<PASSWORD>',
),
),
'retailer' => array(
'alias' => '單位人員管理',
'method' => array(
'overview' => '單位人員列表',
'add' => '新增人員帳號',
'edit' => '編輯人員帳號',
'cancel' => '刪除人員帳號',
),
),
'supervisor' => array(
'alias' => '經銷商列表',
'method' => array(
'overview' => '經銷商列表',
'info' => '經銷單位基本資料',
'purchase' => '經銷商進貨明細',
'detail' => '進貨單詳細資料',
),
),
);
<file_sep>/application/controllers/Retailer.php
<?php
class Retailer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('dealer_model');
$this->session->set_userdata('return_page', base_url('/retailer/overview'));
}
public function overview()
{
$total_dealers_count = $this->dealer_model
->where('retailer_id', $this->dealer['retailer_id'])
->where('isLocked', 0)
->count_rows();
$dealers = $this->dealer_model
->with_group()
->where('retailer_id', $this->dealer['retailer_id'])
->where('isLocked', 0)
->order_by('id', 'desc')
->paginate(20, $total_dealers_count);
$this->load->helper('data_format');
//權限設定
$authority = array();
if ($this->authentic->authority('retailer', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('retailer', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('retailer', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'dealers' => $dealers,
'pagination' => $this->dealer_model->all_pages,
'authority' => $authority,
'title' => $this->dealer['company'] . '人事管理',
'view' => 'retailer/overview',
];
$this->_preload($data);
}
public function add()
{
$this->load->model('retailer_group_model');
$groups = $this->retailer_group_model->getGroupSelect($this->dealer['retailer_role_id'], (empty($this->dealer['level']['type_id']) ? null : $this->dealer['level']['type_id']));
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
$this->form_validation->set_rules('account', '帳號', 'required|alpha_numeric|min_length[3]|max_length[10]|valid_dealer_account');
$this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
$this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
if ($this->form_validation->run() !== FALSE) {
$insert_data = [
'retailer_id' => $this->dealer['retailer_id'],
'retailer_group_id' => $this->input->post('retailer_group_id'),
'account' => $this->input->post('account'),
'password' => $<PASSWORD>->authentic->_mix($this->input->post('password')),
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
];
$this->dealer_model->insert($insert_data);
redirect(base_url('/retailer/overview'));
}
}
$data = [
'groups' => $groups,
'title' => '新增人員帳號',
'view' => 'retailer/add',
];
$this->_preload($data);
}
public function edit($dealer_id)
{
$this->load->model('retailer_group_model');
$groups = $this->retailer_group_model->getGroupSelect($this->dealer['retailer_role_id'], (empty($this->dealer['level']['type_id']) ? null : $this->dealer['level']['type_id']));
$ddealer = $this->dealer_model
->with_retailer()
->get($dealer_id);
if (!$dealer_id || !$ddealer) {
show_error('查無人員資料');
}
if ($ddealer['isLocked']){
show_error('此人員不能刪除');
}
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
$this->form_validation->set_rules('password', '密碼', '<PASSWORD>]');
$this->form_validation->set_rules('password_confirm', '<PASSWORD>', '<PASSWORD>[6]|matches[password]');
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
if ($this->form_validation->run() !== FALSE) {
$update_data = [
'retailer_group_id' => $this->input->post('retailer_group_id'),
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
];
if ($this->input->post('password')){
$update_data['password'] = $this->authentic->_mix($this->input->post('password'));
}
$this->dealer_model->update($update_data, ['id' => $dealer_id]);
redirect(base_url('/retailer/overview'));
}
}
$data = [
'groups' => $groups,
'ddealer' => $ddealer,
'title' => '編輯人員帳號',
'view' => 'retailer/edit',
];
$this->_preload($data);
}
public function cancel($dealer_id)
{
$dealer = $this->dealer_model
->get($dealer_id);
if (!$dealer_id || !$dealer) {
show_error('查無經銷人員資料');
}
if ($dealer_id == $this->dealer['id']){
show_error('不能刪除自己');
}
if ($dealer['isLocked']){
show_error('此經銷人員不能刪除');
}
$retailer = $this->retailer_model
->get($dealer['retailer_id']);
if ($retailer && $retailer['contact_dealer_id'] == $dealer_id){
show_error('預設人員不能刪除');
}
$this->dealer_model->delete($dealer_id);
redirect(base_url('/retailer/overview'));
}
}
?><file_sep>/application/controllers/Index.php
<?php
class Index extends MY_Controller
{
protected $title, $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
}
public function index()
{
$data = [
'title' => '首頁',
'view' => 'welcome',
];
// print_r($this->dealer);
$this->_preload($data);
}
}
?><file_sep>/application/controllers/Capital_retailer_group.php
<?php
class Capital_retailer_group extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_role_model');
$this->load->model('retailer_level_type_model');
$this->load->model('retailer_group_model');
$this->session->set_userdata('return_page', base_url('/capital_retailer_group/overview'));
}
public function overview($id)
{
$tmp = explode('_', $id);
$role = [];
if (!empty($tmp[0])){
$retailer_role_id = (int)$tmp[0];
$retailer_level_type_id = empty($tmp[1]) ? null : (int)$tmp[1];
$role = $this->retailer_role_model
->with_level_types()
->get($retailer_role_id);
if ($retailer_role_id && $role){
if ($role['level_types'] || $retailer_level_type_id){
$level_type = $this->retailer_level_type_model
->where('retailer_role_id', $retailer_role_id)
->get($retailer_level_type_id);
if (!$retailer_level_type_id || !$level_type){
show_error('查無單位類型資料');
} else {
$role['title'] = $level_type['title'];
}
}
}
}
if (!$role){
show_error('查無單位類型資料');
}
if ($retailer_level_type_id){
$this->retailer_group_model->where('retailer_level_type_id', $retailer_level_type_id);
}
$groups = $this->retailer_group_model
->where('retailer_role_id', $retailer_role_id)
->get_all();
//權限設定
$authority = array();
if ($this->authentic->authority('capital_retailer_group', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_retailer_group', 'edit')){
$authority['edit'] = true;
}
$data = [
'id' => $id,
'role' => $role,
'groups' => $groups,
'authority' => $authority,
'title' => '群組總覽',
'view' => 'capital/retailer/group/overview',
];
$this->_preload($data);
}
public function add($id)
{
$tmp = explode('_', $id);
$role = [];
if (!empty($tmp[0])){
$retailer_role_id = (int)$tmp[0];
$retailer_level_type_id = empty($tmp[1]) ? null : (int)$tmp[1];
$role = $this->retailer_role_model
->with_level_types()
->get($retailer_role_id);
if ($retailer_role_id && $role){
if ($role['level_types'] || $retailer_level_type_id){
$level_type = $this->retailer_level_type_model
->where('retailer_role_id', $retailer_role_id)
->get($retailer_level_type_id);
if (!$retailer_level_type_id || !$level_type){
show_error('查無單位類型資料');
} else {
$role['title'] = $level_type['title'];
}
}
}
}
if (!$role){
show_error('查無單位類型資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');
if ($this->form_validation->run() !== FALSE) {
$insert_data = [
'title' => $this->input->post('title'),
'retailer_role_id' => $retailer_role_id,
'retailer_level_type_id' => $retailer_level_type_id,
];
$this->retailer_group_model->insert($insert_data);
redirect(base_url('/capital_retailer_group/overview/' . $id));
}
}
$data = [
'id' => $id,
'role' => $role,
'title' => '新增群組',
'view' => 'capital/retailer/group/add',
];
$this->_preload($data);
}
public function edit($group_id)
{
$group = $this->retailer_group_model
->get($group_id);
if (!$group_id || !$group) {
show_error('查無群組資料');
}
if ($group['retailer_role_id'] == 5) {
$overview_url = base_url('/capital_retailer_group/overview/' . $group['retailer_role_id'] . '_' . $group['retailer_level_type_id']);
} else {
$overview_url = base_url('/capital_retailer_group/overview/' . $group['retailer_role_id']);
}
if ($this->input->post()) {
$this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');
if ($this->form_validation->run() !== FALSE) {
$update_data = [
'title' => $this->input->post('title'),
];
$this->retailer_group_model->update($update_data, ['id' => $group_id]);
redirect($overview_url);
}
}
$data = [
'group' => $group,
'overview_url' => $overview_url,
'title' => '編輯群組',
'view' => 'capital/retailer/group/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/models/Purchase_item_model.php
<?php
class Purchase_item_model extends MY_Model
{
public $table = 'olive_purchase_items';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
$this->has_one['product'] = array('foreign_model' => 'Product_model', 'foreign_table' => 'product', 'foreign_key' => 'pdId', 'local_key' => 'product_id');
}
public function getPurchaseItemOfId($purchase_id, $product_id)
{
return $this
->with_purchase()
->where('purchase_id', $purchase_id)
->where('product_id', $product_id)
->get();
}
}
?>
<file_sep>/application/models/Product_kind_model.php
<?php
class Product_kind_model extends MY_Model{
public $table = 'product_kind';
public $primary_key = 'ctId';
function __construct(){
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
}
public function getKindSelect()
{
$_kinds = $this
->where('ctId', [3,6])
->get_all();
$kinds = [];
foreach ($_kinds as $kind){
$kinds[$kind['ctId']] = $kind['ctName'];
}
return $kinds;
}
}
?>
<file_sep>/application/views/shipment/revise_edit.php
<div class="container">
<h1 class="mb-4">編輯銷貨異動</h1>
<form method="post" id="shipmentForm" enctype="multipart/form-data">
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號 / 貨品名稱</th>
<th>訂購數量</th>
<th>到期日</th>
<th>出貨數量</th>
<th>收貨數量</th>
<th>備註</th>
<th>照片</th>
</tr>
<?php
if ($shipment['items']) {
$i = 1;
foreach ($shipment['items'] as $item) {
if (empty($products[$item['product_id']])){
continue;
}
$stock_row = count($products[$item['product_id']]);
?>
<tr>
<td class="text-center" rowspan="<?=$stock_row?>"><?= $i ?></td>
<td rowspan="<?=$stock_row?>"><?= $item['product']['p_num'] ?> <br /><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td class="text-right" rowspan="<?=$stock_row?>"><?= number_format($item['qty']) ?></td>
<?php
foreach ($products[$item['product_id']] as $key => $stock){
if ($key > 0){
echo '</tr><tr>';
}
?>
<td><?=$stock['expired_at'] ? $stock['expired_at'] : '未標示'?></td>
<td class="text-right"><?= $stock['qty'] ?></td>
<td class="text-center">
<input type="number" min="0" data-stock="<?=$stock['qty']?>" class="input_qty form-control text-right" name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][qty]" value="<?= empty($stock['revise']) ? $stock['qty'] : $stock['revise']['qty'] ?>" style="width: 120px;" />
</td>
<td class="text-center">
<textarea disabled name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][memo]" class="text_qty_memo form-control" style="min-width: 120px;"><?= empty($stock['revise']) ? '' : $stock['revise']['memo'] ?></textarea>
</td>
<td>
<input type="hidden" name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][memo_file]" value="<?= empty($stock['revise']) ? '' : $stock['revise']['memo_file'] ?>" />
<input disabled type="file" class="input_qty_file form-control-file" name="memo_pictures[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>]" style="min-width: 120px;" />
<?php if (!empty($stock['revise']['memo_file'])){ ?>
<br /><a href="<?=$stock['revise']['memo_file']?>" target="_blank" class="btn btn-info">附件</a>
<?php } ?>
</td>
<?php } ?>
</tr>
<?php
$i++;
}
}
?>
</table>
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group text-center">
<a href="<?=base_url('/purchase/detail/' . $shipment['ship_id'])?>" class="btn btn-secondary">取消</a>
<input type="submit" name="confirmed" class="btn btn-success" value="更新銷貨異動"/>
</div>
</form>
</div>
<script>
$().ready(function () {
$('.input_qty').change(function(){
var shipin_qty = parseInt($(this).val()) || 0;
var stock_qty = parseInt($(this).data('stock')) || 0;
if (shipin_qty != stock_qty){
$(this).parents('tr').find('.text_qty_memo').prop('disabled', false);
$(this).parents('tr').find('.input_qty_file').prop('disabled', false);
} else {
$(this).parents('tr').find('.text_qty_memo').prop('disabled', true);
$(this).parents('tr').find('.input_qty_file').prop('disabled', true);
}
});
$('.input_qty').trigger('change');
$("#shipmentForm").submit(function (e) {
$.each($('input.input_qty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('textarea.text_qty_memo'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('input.input_qty_file'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
});
});
</script><file_sep>/application/controllers/Capital_relationship_shipout.php
<?php
class Capital_relationship_shipout extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('retailer_relationship_model');
$this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
}
public function overview($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無單位資料!');
}
$total_relationships_count = $this->retailer_relationship_model
->with_relation()
->where('relation_type', 'shipout')
->where('retailer_id', $retailer_id)
->count_rows();
$relationships = $this->retailer_relationship_model
->with_relation()
->where('relation_type', 'shipout')
->where('retailer_id', $retailer_id)
->order_by('relation_retailer_id')
->paginate(20, $total_relationships_count);
$this->load->helper('data_format');
//權限設定
$authority = array();
if ($this->authentic->authority('capital_relationship_shipout', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_relationship_shipout', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_product_relationship', 'edit')){
$authority['product'] = true;
}
if ($this->authentic->authority('capital_relationship_shipout', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'retailer' => $retailer,
'relationships' => $relationships,
'pagination' => $this->retailer_relationship_model->all_pages,
'authority' => $authority,
'title' => $retailer['company'] . '出貨關係單位',
'view' => 'capital/relationship/shipout/overview',
];
$this->_preload($data);
}
public function add($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無單位資料!');
}
$retailer_selects = $this->retailer_model->getRetailerSelect();
if ($this->input->post()) {
$this->form_validation->set_rules('relation_retailer_id', '出貨單位', 'required|integer|in_list[' . implode(',',array_keys($retailer_selects)) . ']');
$this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
if ($this->form_validation->run() !== FALSE) {
$this->retailer_relationship_model->insert([
'relation_type' => 'shipout',
'retailer_id' => $retailer_id,
'relation_retailer_id' => $this->input->post('relation_retailer_id'),
'discount' => $this->input->post('discount'),
]);
redirect(base_url('/capital_relationship_shipout/overview/' . $retailer_id));
}
}
$this->load->helper('form');
$data = [
'retailer' => $retailer,
'retailer_selects' => $retailer_selects,
'title' => '新增出貨關係單位',
'view' => 'capital/relationship/shipout/add',
];
$this->_preload($data);
}
public function edit($relationship_id)
{
$relationship = $this->retailer_relationship_model
->with_retailer()
->with_relation()
->get($relationship_id);
if (!$relationship_id || !$relationship) {
show_error('查無出貨關係單位資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
if ($this->form_validation->run() !== FALSE) {
$this->retailer_relationship_model->update([
'discount' => $this->input->post('discount'),
], ['id' => $relationship_id]);
redirect(base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id']));
}
}
$data = [
'relationship' => $relationship,
'title' => '編輯出貨關係單位',
'view' => 'capital/relationship/shipout/edit',
];
$this->_preload($data);
}
public function cancel($relationship_id)
{
$relationship = $this->retailer_relationship_model
->get($relationship_id);
if (!$relationship_id || !$relationship) {
show_error('查無出貨關係單位資料');
}
$this->retailer_relationship_model->delete($relationship_id);
redirect(base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id']));
}
}
?><file_sep>/application/views/capital/option/customer.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">編輯消費者參數</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>員工每季消費上限</label>.
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" name="customer_staff_max_amount" class="form-control text-right" value="<?= set_value('customer_staff_max_amount', isset($options['customer_staff_max_amount']) ? $options['customer_staff_max_amount'] : '') ?>" required min="0" />
</div>
</div>
<div class="form-group d-flex justify-content-between">
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/migrations/064_update_consumer_send_address.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_consumer_send_address extends CI_Migration {
public function up()
{
$this->dbforge->add_column('olive_order_contacts', [
'altAddress' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'after' => 'address',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_order_contacts', 'altAddress');
}
}<file_sep>/application/models/Retailer_relationship_model.php
<?php
class Retailer_relationship_model extends MY_Model
{
public $table = 'olive_retailer_relationships';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['relation'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'relation_retailer_id');
$this->has_one['alter'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'alter_retailer_id');
}
}
?>
<file_sep>/application/controllers/Auth.php
<?php
class Auth extends MY_Controller
{
public function __construct()
{
parent::__construct();
$except_method = ['loginCheck', 'validate_credentialsAjax', 'logout'];
if ($this->authentic->isLogged() && !in_array($this->router->fetch_method(), $except_method)) {
redirect(base_url('/'));
}
}
public function register()
{
if ($this->input->post()) {
$this->form_validation->set_rules('account', '輔銷人之經銷商代號', 'trim|required');
$this->form_validation->set_rules('password', '密碼', 'trim|required|callback_check_authentic');
if ($this->form_validation->run() !== FALSE) {
$this->session->set_userdata('guest', [
'admin_check_discount' => false,
'sales_retailer' => [], //輔銷單位
'sales_dealer' => $this->authentic->isLogged(), //輔銷人
'retailer' => [
'account' => '',
'company' => '',
'identity' => '',
'contact' => '',
'gender' => 1,
'phone' => '',
'altPhone' => '',
'address' => '',
],
'purchase' => [
'cart' => [],
'total' => 0,
'memo' => '',
],
]);
redirect(base_url('/guest/level'), 'refresh');
}
}
$data = [
'title' => '輔銷人登入',
'view' => 'auth/register',
];
$this->_preload($data, 'login');
}
public function login()
{
if ($this->input->post()) {
$this->form_validation->set_rules('account', '代號', 'trim|required');
$this->form_validation->set_rules('password', '密碼', 'trim|required|callback_check_authentic');
if ($this->form_validation->run() !== FALSE) {
$return_page = $this->session->userdata('return_page');
if ($return_page) {
$this->session->unset_userdata('return_page');
redirect(base_url($return_page), 'refresh');
} else {
redirect(base_url('/'), 'refresh');
}
}
}
$data = [
'title' => '登入',
'view' => 'auth/login',
];
$this->_preload($data, 'login');
}
public function check_authentic($password)
{
if ($this->authentic->authenticate($this->input->post('account'), $password)) {
return true;
} else {
$this->form_validation->set_message('check_authentic','您輸入的帳號密碼錯誤,請重新確認');
return false;
}
}
public function logout()
{
$this->authentic->logout();
$this->session->set_userdata(array('msg' => '您已經成功登出'));
redirect('/');
}
//驗證登入狀態
public function loginCheck()
{
if ($this->authentic->isLogged()){
echo 'ok';
} else {
echo 'error';
}
}
public function validate_credentialsAjax()
{
if ($this->input->post()) {
$this->form_validation->set_rules('account', '代號', 'trim|required');
$this->form_validation->set_rules('password', '密碼', 'trim|required|callback_<PASSWORD>');
if ($this->form_validation->run() == FALSE) {
$error_data = array(
'error' => validation_errors(),
);
echo json_encode($error_data);
} else {
$success_data = array(
'dealer' => $this->authentic->isLogged(),
);
echo json_encode($success_data);
}
}
$error_data = array(
'error' => '非法登入',
);
echo json_encode($error_data);
}
}
?><file_sep>/application/models/Recommend_model.php
<?php
class Recommend_model extends MY_Model
{
public $table = 'olive_recommends';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['template'] = array('foreign_model' => 'Recommend_template_model', 'foreign_table' => 'olive_recommend_templates', 'foreign_key' => 'id', 'local_key' => 'recommend_template_id');
}
}
?>
<file_sep>/application/controllers/Consumer.php
<?php
class Consumer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
$this->load->model('customer_model');
$this->load->model('old_customer_model');
$this->load->model('order_model');
$this->load->model('shipment_model');
$this->load->model('shipment_item_model');
$this->load->model('shipment_expiration_model');
$this->load->model('payment_model');
$this->load->model('order_return_model');
$this->load->model('order_return_item_model');
$this->load->model('order_transfer_model');
$this->load->model('stock_model');
$this->load->library('customer_lib');
$this->load->library('stock_lib');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/consumer/overview'));
$this->payment_type = [
1 => '現金付款取貨',
3 => '信用卡付款取貨',
4 => '貨到付款',
5 => '其他門市取貨',
];
}
public function index()
{
//權限設定
$authority = array();
if ($this->authentic->authority('customer', 'overview')) {
$authority['customer'] = true;
}
if ($this->authentic->authority('consumer', 'overview')) {
$authority['consumer'] = true;
}
if ($this->authentic->authority('coupon', 'overview')) {
$authority['coupon'] = true;
}
$data = [
'authority' => $authority,
'title' => '消費者歷史消費紀錄',
'view' => 'consumer/index',
];
$this->_preload($data);
}
public function overview()
{
$total_orders_count = $this->order_model
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->count_rows();
$orders = $this->order_model
->with_contact()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->order_by($this->order_model->get_table_name() . '.id', 'desc')
->paginate(20, $total_orders_count);
//權限設定
$authority = array();
if ($this->authentic->authority('customer', 'consumer')) {
$authority['customer'] = true;
}
if ($this->authentic->authority('consumer', 'detail')) {
$authority['detail'] = true;
}
if ($this->authentic->authority('consumer', 'trashed')) {
$authority['trashed'] = true;
}
if ($this->authentic->authority('consumer', 'edit')) {
$authority['edit'] = true;
}
if ($this->authentic->authority('consumer', 'cancel')) {
$authority['cancel'] = true;
}
$data = [
'orders' => $orders,
'pagination' => $this->order_model->all_pages,
'authority' => $authority,
'title' => '銷售單位歷史銷售',
'view' => 'consumer/overview',
];
$this->_preload($data);
}
public function trashed()
{
$total_orders_count = $this->order_model
->only_trashed()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->count_rows();
$orders = $this->order_model
->only_trashed()
->with_contact()
->with_dealer(['with' => ['relation' => 'trashed']])
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->order_by($this->order_model->get_table_name() . '.id', 'desc')
->paginate(20, $total_orders_count);
//權限設定
$authority = array();
if ($this->authentic->authority('consumer', 'detail')) {
$authority['detail'] = true;
}
if ($this->authentic->authority('consumer', 'recover')) {
$authority['recover'] = true;
}
$data = [
'orders' => $orders,
'pagination' => $this->order_model->all_pages,
'authority' => $authority,
'title' => '取消之消費紀錄',
'view' => 'consumer/trashed',
];
$this->_preload($data);
}
public function detail($order_id)
{
$order = $this->order_model
->with_trashed()
->where('buyer_type', 'customer')
->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
->with_customer(['with' => ['relation' => 'level']])
->with_shipout_retailer()
->with_dealer(['with' => ['relation' => 'trashed']])
->with_contact()
->with_recipient()
->get($order_id);
if (!$order_id || !$order) {
show_error('查無消費紀錄');
}
$this->load->helper('data_format');
$shipment = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
->where('ship_type', 'consumer')
->where('ship_id', $order_id)
->where('isConfirmed', 1)
->get();
$data = [
'order' => $order,
'shipment' => $shipment,
'title' => '消費者消費明細',
'view' => 'consumer/detail',
];
$this->_preload($data);
}
public function old()
{
if ($this->input->post()) {
$this->form_validation->set_rules('name', '姓名', 'max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'is_natural|max_length[20]|callback_check_oldCustomer[' . $this->input->post('name') . ']');
if ($this->form_validation->run() !== FALSE) {
$this->old_customer_model->group_start();
if (!empty($this->input->post('phone'))) {
$this->old_customer_model->where('phone', $this->input->post('phone'), null, true);
}
if (!empty($this->input->post('name'))) {
$this->old_customer_model->where('name', $this->input->post('name'), null, true);
}
$customer = $this->old_customer_model->group_end()->where('isActive', 0)->get();
if (!empty($_POST['submit_buy'])) {
redirect(base_url('/consumer/add/old_' . $customer['id']));
} else {
redirect(base_url('/customer/conv_old/' . $customer['id']));
}
}
}
$data = [
'title' => '舊有會員轉換',
'view' => 'consumer/old',
];
$this->_preload($data);
}
public function check_oldCustomer($phone, $name)
{
$error = '';
if (empty($phone) && empty($name)) {
$error = '查無舊有會員';
} else {
$this->old_customer_model->group_start();
if (!empty($phone)) {
$this->old_customer_model->where('phone', $phone, null, true);
}
if (!empty($name)) {
$this->old_customer_model->where('name', $name, null, true);
}
$customer = $this->old_customer_model->group_end()->get();
if (!$customer) {
$error = '查無舊有會員';
} else {
if ($customer['isActive']) {
$error = '此舊有會員已轉換';
}
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_oldCustomer', $error);
return false;
}
}
public function add($customer_id = '')
{
$this->load->model('promote_model');
$this->load->model('promote_use_model');
$this->load->model('product_model');
$this->load->model('combo_model');
$this->load->model('free_package_item_model');
$this->load->model('option_model');
$customer = [];
$discount_type = 'P';
$discount = $member_discount = 100;
$old_customer = false;
$option = $this->option_model
->where('name', 'customer_staff_max_amount')
->get();
$staff_max_amount = !empty($option['value']) ? (int)$option['value'] : null;
if ($customer_id) {
$tmp = explode('_', $customer_id);
if (!empty($tmp[0]) && $tmp[0] == 'old') {
$old_customer = true;
if (!empty($tmp[1])) {
$old_customer_id = $tmp[1];
$old_customer = $this->old_customer_model
->with_customer()
->get($old_customer_id);
if (!$old_customer) {
show_error('查無舊有會員');
} else {
if ($old_customer['isActive']) {
redirect(base_url('/consumer/add/' . $old_customer['customer']['id']));
} else {
$this->load->model('customer_level_model');
$level2_data = $this->customer_level_model->get(2);
$member_discount = $level2_data['discount'];
$customer = [
'old_customer_id' => $old_customer_id,
'isDealer' => 0,
'name' => $old_customer['name'],
'gender' => $old_customer['gender'],
'phone' => $old_customer['phone'],
'address' => $old_customer['address'],
'email' => $old_customer['email'],
'level' => [
'title' => $level2_data['title'],
],
'created_at' => date('Y-m-d H:i:s'),
];
}
}
} else {
show_error('查無舊有會員');
}
} elseif ($customer_id) {
$this->customer_lib->setCustomerID($customer_id);
$this->customer_lib->downgradeCheckCustomerLevel();
$customer = $this->customer_lib->getCustomer();
if (!$customer) {
show_error('查無消費者');
}
if (!empty($customer['level']['discount'])) {
$member_discount = $customer['level']['discount'];
}
if ($customer['isDealer']) {
if (!is_null($staff_max_amount)) {
$season = $this->customer_lib->getCurrentSeasonRange();
$order_table = $this->order_model->get_table_name();
$total_orders_data = $this->order_model
->fields('SUM(' . $order_table . '.total) as total')
->where('buyer_type', 'customer')
->where('buyer_id', $customer_id)
->where('created_at', '>=', $season[0])
->where('created_at', '<=', $season[1])
->get();
if ($total_orders_data) {
if ($staff_max_amount >= $total_orders_data['total']) {
$staff_max_amount -= $total_orders_data['total'];
} else {
$staff_max_amount = 0;
}
}
}
}
}
}
$promotes = $this->promote_model->getActivePromotes($this->dealer['retailer_id'], $customer);
$products = $this->product_model->getCustomerProducts();
$_combos = $this->combo_model
->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'pao']]])
->get_all();
$_free_packages = $this->free_package_item_model
->with_product(['with' => ['relation' => 'pao']])
->get_all();
$combos = [];
$free_packages = [];
if ($this->dealer['hasStock']) {
foreach ($products as $product_id => $product) {
$stocks = $this->stock_model
->where('product_id', $product_id)
->where('retailer_id', $this->dealer['retailer_id'])
->where('stock', '>', 0)
->group_start()
->where('expired_at', '>=', date('Y-m-d'), true)
->where('expired_at IS NULL', null, null, true, false, true)
->group_end()
->order_by('ISNULL(expired_at)', 'asc')
->order_by('expired_at', 'asc')
->get_all();
$product_stock = $this->product_model->calcStock($stocks, $product);
$products[$product_id]['expired_at'] = empty($stocks[0]['expired_at']) ? '' : $stocks[0]['expired_at'];
$products[$product_id]['stock'] = $product_stock['active_total'];
}
if ($_combos) {
foreach ($_combos as $combo) {
$combo_max_stock = null;
foreach ($combo['items'] as $key => $item) {
$stocks = $this->stock_model
->where('product_id', $item['product_id'])
->where('retailer_id', $this->dealer['retailer_id'])
->where('stock', '>', 0)
->order_by('expired_at', 'asc')
->get_all();
$combo['items'][$key]['stock'] = $this->product_model->calcStock($stocks, $item['product']);
if (is_null($combo_max_stock)) {
$combo_max_stock = $combo['items'][$key]['stock']['active_total'];
} else {
$combo_max_stock = min($combo_max_stock, $combo['items'][$key]['stock']['active_total']);
}
}
$combo['stock'] = $combo_max_stock ? $combo_max_stock : 0;
$combos[$combo['id']] = $combo;
}
}
if ($_free_packages) {
foreach ($_free_packages as $free_package) {
$stocks = $this->stock_model
->where('product_id', $free_package['product_id'])
->where('retailer_id', $this->dealer['retailer_id'])
->where('stock', '>', 0)
->order_by('expired_at', 'asc')
->get_all();
$product_stock = $this->product_model->calcStock($stocks, $free_package['product']);
$free_package['stock'] = $product_stock['active_total'];
$free_packages[$free_package['product_id']] = $free_package;
}
}
}
$shipout_retailers = [];
if ($this->dealer['retailer_role_id'] == 4) {
$this->load->library('purchase_lib');
$purchase_lib = new purchase_lib();
$shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);
if (!$shipout_retailers) {
unset($this->payment_type[5]);
}
} else {
unset($this->payment_type[5]);
}
if ($this->input->post()) {
if (!empty($customer['customer_level_id']) || $old_customer) {
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
$this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
$this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
$this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
} else {
if (!empty($_POST['hide_customer_info'])) {
$this->form_validation->set_rules('reason', '顧客為何無留下完整資料', 'required|min_length[10]|max_length[50]');
} else {
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
$this->form_validation->set_rules('gender', '性別', 'integer|in_list[0,1]');
$this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
$this->form_validation->set_rules('birthday', '生日', 'valid_date');
$this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
$this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
}
}
$this->form_validation->set_rules('altAddress', '收貨地址', 'max_length[100]');
$this->form_validation->set_rules('isDealer', '是否員工', 'integer');
$this->form_validation->set_rules('coupon_number_1', '滿$2000核發折價券', 'max_length[30]|callback_check_coupon');
$this->form_validation->set_rules('coupon_number_2', '滿$6000核發折價券', 'max_length[30]|callback_check_coupon');
$this->form_validation->set_rules('payment_type', '付款方式', 'required|integer|in_list[' . implode(',', array_keys($this->payment_type)) . ']');
if (!empty($_POST['payment_type'])) {
if ($_POST['payment_type'] == '4') { //貨到付款
$this->form_validation->set_rules('recipient_name', '收件人姓名', 'required|max_length[20]');
$this->form_validation->set_rules('recipient_phone', '收件人電話', 'required|is_natural|max_length[20]');
$this->form_validation->set_rules('recipient_address', '收件人地址', 'required|max_length[100]');
} elseif ($_POST['payment_type'] == '5') { //其他門市取貨
$this->form_validation->set_rules('shipout_retailer_id', '取貨門市', 'required|integer|in_list[' . implode(',', array_keys($shipout_retailers)) . ']');
}
}
$check_qty_options = [
'products' => $products,
'items' => $this->input->post('items'),
'expired_dates' => $this->input->post('expired_dates'),
'combos' => $combos,
'combo_items' => $this->input->post('combo_items'),
'packages' => $free_packages,
'package_items' => $this->input->post('package_items'),
'payment_type' => $this->input->post('payment_type'),
];
$promote_types = [];
if (!empty($_POST['promote_type'])) {
$promote_types = (array)$_POST['promote_type'];
if ($promote_types) {
if (in_array(1, $promote_types)) { //會員優惠
$discount = $member_discount;
}
if (in_array(2, $promote_types)) { //優惠活動
$this->form_validation->set_rules('promote_id', '優惠活動', 'required|integer|callback_check_promote[' . json_encode(['isDealer' => $this->input->post('isDealer'), 'promotes' => $promotes]) . ']');
$check_qty_options['gift_items'] = $this->input->post('gift_items');
$check_qty_options['promotes'] = $promotes;
$check_qty_options['promote_id'] = $this->input->post('promote_id');
}
if (in_array(3, $promote_types)) { //使用貴賓優惠券
$this->form_validation->set_rules('coupon_used', '使用貴賓優惠券', 'required|max_length[30]');
}
}
}
$this->form_validation->set_rules('items[][qty]', '貨品訂購數量', 'callback_check_qty[' . json_encode($check_qty_options) . ']');
if ($this->form_validation->run() !== FALSE) {
$buyer_name = $this->input->post('name');
$buyer_phone = $this->input->post('phone');
$buyer_address = $this->input->post('address');
$isDealer = empty($this->input->post('isDealer')) ? 0 : 1;
if (!empty($customer['id'])) {
$customer_id = $customer['id'];
$update_data = [
'isDealer' => $isDealer,
'name' => $buyer_name,
'gender' => $this->input->post('gender') !== '' ? $this->input->post('gender') : null,
'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
'email' => $this->input->post('email') ? $this->input->post('email') : null,
'phone' => $buyer_phone,
'address' => $buyer_address,
];
$this->customer_model->update($update_data, ['id' => $customer_id]);
} else {
if ($buyer_name && $buyer_phone && $buyer_address) {
$insert_data = [
'isDealer' => $isDealer,
'name' => $buyer_name,
'gender' => $this->input->post('gender') !== '' ? $this->input->post('gender') : null,
'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
'email' => $this->input->post('email') ? $this->input->post('email') : null,
'phone' => $buyer_phone,
'address' => $buyer_address,
];
//舊有會員轉換
if ($old_customer) {
$insert_data['old_customer_id'] = $old_customer_id;
}
$customer_id = $this->customer_model->insert($insert_data);
}
}
$this->load->model('order_contact_model');
$this->load->model('order_item_model');
$this->load->model('coupon_approve_model');
$orderSerialNum = $this->order_model->getNextOrderSerialNum();
$isPaid = 0;
$isShipped = 0;
switch ($this->input->post('payment_type')) {
case 4:
break;
case 5:
$isPaid = 1;
break;
default:
$isPaid = 1;
$isShipped = 1;
break;
}
$memo = null;
if (!empty($_POST['hide_customer_info'])) {
$memo = $this->input->post('reason');
}
if ($this->input->post('memo')) {
if ($memo) {
$memo .= PHP_EOL;
}
$memo .= $this->input->post('memo');
}
$orderNum = date('Ym') . $orderSerialNum;
$order_id = $this->order_model->insert([
'buyer_type' => 'customer',
'buyer_id' => $customer_id ? $customer_id : null,
'shipout_retailer_id' => $this->dealer['retailer_id'],
'serialNum' => $orderSerialNum,
'orderNum' => $orderNum,
'couponNum' => empty($this->input->post('coupon_used')) ? null : $this->input->post('coupon_used'),
'dealer_id' => $this->dealer['id'],
'isConfirmed' => 1,
'isPaid' => $isPaid,
'isShipped' => $isShipped,
'memo' => $memo,
]);
if ($customer_id) {
$this->order_contact_model->insert([
'order_id' => $order_id,
'name' => $buyer_name,
'phone' => $buyer_phone,
'address' => $this->input->post('address') ? $this->input->post('address') : null,
'altAddress' => $this->input->post('altAddress') ? $this->input->post('altAddress') : null,
]);
}
if ($this->input->post('payment_type') == '4') { //貨到付款
$this->load->model('order_recipient_model');
$this->order_recipient_model->insert([
'order_id' => $order_id,
'name' => $this->input->post('recipient_name'),
'phone' => $this->input->post('recipient_phone'),
'address' => $this->input->post('recipient_address'),
]);
}
//出貨
if ($isShipped) {
$shipment_id = $this->shipment_model->insert([
'ship_type' => 'consumer',
'ship_id' => $order_id,
'shipout_retailer_id' => $this->dealer['retailer_id'],
'shipin_retailer_id' => null,
'eta_at' => date('Y-m-d'),
'memo' => null,
'isConfirmed' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
//紀錄產品有效期限
$expired_dates = (array)$this->input->post('expired_dates');
$expired_at_data = [];
foreach ($expired_dates as $product_id => $expired_date) {
if (!isset($expired_at_data[$product_id])) {
$expired_at_data[$product_id] = [];
}
foreach ($expired_date as $expired_at) {
if (!isset($expired_at_data[$product_id][$expired_at])) {
$expired_at_data[$product_id][$expired_at] = 0;
}
$expired_at_data[$product_id][$expired_at]++;
}
}
foreach ($expired_at_data as $product_id => $v) {
foreach ($v as $expired_at => $q) {
$this->shipment_expiration_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $q,
]);
}
}
}
$promote = [];
if (in_array(2, $promote_types)) { //優惠活動
$promote_id = (int)$this->input->post('promote_id');
$promote = (isset($promotes[$promote_id])) ? $promotes[$promote_id] : [];
if ($promote) {
$this->promote_use_model->insert([
'promote_id' => $promote_id,
'customer_id' => $customer_id,
]);
}
}
$items = (array)$this->input->post('items');
$combo_items = (array)$this->input->post('combo_items');
$package_items = (array)$this->input->post('package_items');
$subtotal = 0;
$total = 0;
$totalDiscount = 0;
$totalReachDiscount = 0;
if ($items) {
foreach ($items as $product_id => $item) {
if (!$item['qty']) continue;
$item_discount = $discount;
$item_discount_type = $discount_type;
$price = $products[$product_id]['pdCash'];
$item_subtotal = $item['qty'] * $price;
if ($item_discount_type == 'P') {
$item_total = round($item_subtotal * $item_discount / 100);
} else {
$item_total = $item_subtotal - $item_discount;
$item_discount = round($item_total / $item_subtotal * 100);
}
if ($promote) {
foreach ($promote['methods'] as $key => $method) {
switch ($method['promote_type_id']) {
case 1: //產品折扣
$item_match = false;
if (empty($method['items'])) {
$item_match = true;
} else {
foreach ($method['items'] as $pitem) {
if ($pitem['id'] == $product_id) {
$item_match = true;
break;
}
}
}
if ($item_match) {
if ($method['discount_type'] == 'P') {
$item_total = round($item_total * $method['discount'] / 100);
$item_discount = round($item_total / $item_subtotal * 100);
} else {
$item_total -= $method['discount'];
$item_discount = round($item_total / $item_subtotal * 100);
}
}
break;
case 2: //滿額折扣
$item_match = false;
if (!empty($method['items'])) {
foreach ($method['items'] as $pitem) {
if ($pitem['id'] == $product_id) {
$item_match = true;
break;
}
}
} else {
$item_match = true;
}
if ($item_match) {
if (!isset($promote['methods'][$key]['totalDiscount'])) {
$promote['methods'][$key]['totalDiscount'] = 0;
}
$promote['methods'][$key]['totalDiscount'] += $item_total;
}
break;
case 3: //贈品
$item_match = false;
if (!empty($method['relatives'])) {
foreach ($method['relatives'] as $pitem) {
if ($pitem['type'] == 'product' && $pitem['id'] == $product_id) {
$item_match = true;
break;
}
}
} else {
$item_match = true;
}
if ($item_match) {
if (!isset($promote['methods'][$key]['totalGift'])) {
$promote['methods'][$key]['totalGift'] = 0;
}
$promote['methods'][$key]['totalGift'] += $item_total;
}
break;
}
}
}
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $product_id,
'qty' => $item['qty'],
'price' => $price,
'discount' => $item_discount,
'subPrice' => $item_total,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $product_id,
'qty' => $item['qty'],
]);
}
$subtotal += $item_subtotal;
$totalDiscount += $item_subtotal - $item_total;
$total += $item_total;
}
}
if ($combo_items) {
foreach ($combo_items as $combo_id => $item) {
foreach ($combos[$combo_id]['items'] as $citem) {
if (!$citem['qty']) continue;
$combo_item_discount = $discount;
$combo_item_discount_type = $discount_type;
$combo_item_qty = $citem['qty'] * $item['qty'];
$combo_item_subtotal = $combo_item_qty * $citem['price'];
if ($combo_item_discount_type == 'P') {
$combo_item_total = round($combo_item_subtotal * $combo_item_discount / 100);
} else {
$combo_item_total = $combo_item_subtotal - $combo_item_discount;
$combo_item_discount = round($combo_item_total / $combo_item_subtotal * 100);
}
if ($promote) {
foreach ($promote['methods'] as $key => $method) {
switch ($method['promote_type_id']) {
case 1: //產品折扣
$item_match = false;
if (!empty($method['items'])) {
foreach ($method['items'] as $pitem) {
if ($pitem['type'] == 'combo' && $pitem['id'] == $combo_id) {
$item_match = true;
break;
}
}
} else {
$item_match = true;
}
if ($item_match) {
if ($method['discount_type'] == 'P') {
$combo_item_total = round($combo_item_total * $method['discount'] / 100);
if ($combo_item_subtotal > 0) {
$combo_item_discount = round($combo_item_total / $combo_item_subtotal * 100);
}
} else {
$combo_item_total -= $method['discount'];
if ($combo_item_subtotal > 0) {
$combo_item_discount = round($combo_item_total / $combo_item_subtotal * 100);
}
}
}
break;
case 2: //滿額折扣
$item_match = false;
if (!empty($method['items'])) {
foreach ($method['items'] as $pitem) {
if ($pitem['type'] == 'combo' && $pitem['id'] == $combo_id) {
$item_match = true;
break;
}
}
} else {
$item_match = true;
}
if ($item_match) {
if (!isset($promote['methods'][$key]['totalDiscount'])) {
$promote['methods'][$key]['totalDiscount'] = 0;
}
$promote['methods'][$key]['totalDiscount'] += $combo_item_total;
}
break;
case 3: //贈品
$item_match = false;
if (!empty($method['relatives'])) {
foreach ($method['relatives'] as $pitem) {
if ($pitem['type'] == 'combo' && $pitem['id'] == $combo_id) {
$item_match = true;
break;
}
}
} else {
$item_match = true;
}
if ($item_match) {
if (!isset($promote['methods'][$key]['totalGift'])) {
$promote['methods'][$key]['totalGift'] = 0;
}
$promote['methods'][$key]['totalGift'] += $combo_item_total;
}
break;
}
}
}
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $citem['product_id'],
'qty' => $combo_item_qty,
'price' => $citem['price'],
'discount' => $combo_item_discount,
'subPrice' => $combo_item_total,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $citem['product_id'],
'qty' => $combo_item_qty,
]);
}
$subtotal += $combo_item_subtotal;
$totalDiscount += $combo_item_subtotal - $combo_item_total;
$total += $combo_item_total;
}
}
}
if ($package_items) {
foreach ($package_items as $product_id => $item) {
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $product_id,
'qty' => $item['qty'],
'price' => 0,
'discount' => 100,
'subPrice' => 0,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $product_id,
'qty' => $item['qty'],
]);
}
}
}
if ($promote) {
foreach ($promote['methods'] as $method) {
switch ($method['promote_type_id']) {
case 2: //滿額折扣
if (isset($method['totalDiscount']) && $method['totalDiscount'] >= $method['limit']) {
$totalReachDiscount += $method['discount'];
}
break;
case 3: //贈品
if (isset($method['totalGift']) && $method['totalGift'] >= $method['limit']) {
$options = $method['options'];
if (empty($options['single'])) {
foreach ($method['items'] as $pitem) {
if ($pitem['type'] == 'product') {
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $pitem['id'],
'qty' => 1,
'price' => 0,
'discount' => 100,
'subPrice' => 0,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $pitem['id'],
'qty' => 1,
]);
}
} elseif ($pitem['type'] == 'combo') {
foreach ($combos[$pitem['id']]['items'] as $citem) {
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $citem['product_id'],
'qty' => $citem['qty'],
'price' => 0,
'discount' => 100,
'subPrice' => 0,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $citem['product_id'],
'qty' => $citem['qty'],
]);
}
}
}
}
} else { //擇一贈品
$gift_items = (array)$this->input->post('gift_items');
if ($gift_items && !empty($gift_items[$method['id']])) {
$pitem = explode('-', $gift_items[$method['id']]);
if (!empty($pitem[0]) && !empty($pitem[1])) {
if ($pitem[0] == 'product') {
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $pitem[1],
'qty' => 1,
'price' => 0,
'discount' => 100,
'subPrice' => 0,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $pitem[1],
'qty' => 1,
]);
}
} elseif ($pitem[0] == 'combo') {
foreach ($combos[$pitem[1]]['items'] as $citem) {
$this->order_item_model->insert([
'order_id' => $order_id,
'product_id' => $citem['product_id'],
'qty' => $citem['qty'],
'price' => 0,
'discount' => 100,
'subPrice' => 0,
]);
if ($isShipped) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $citem['product_id'],
'qty' => $citem['qty'],
]);
}
}
}
}
}
}
}
break;
}
}
$total -= $totalReachDiscount;
}
$this->order_model->update([
'subtotal' => $subtotal,
'totalDiscount' => $totalDiscount,
'totalReachDiscount' => $totalReachDiscount,
'total' => $total,
], ['id' => $order_id]);
if ($isShipped) {
//出貨扣庫
$this->stock_lib->shipout_confirm($shipment_id);
}
//付款紀錄
if ($isPaid) {
$this->payment_model->insert([
'pay_type' => 'order',
'pay_id' => $order_id,
'received_retailer_id' => $this->dealer['retailer_id'],
'price' => $total,
'type_id' => $this->input->post('payment_type'),
'active' => 1,
'isConfirmed' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
}
//核發優惠券
if ($total >= 2000) {
if ($this->input->post('coupon_number_1')) {
$this->coupon_approve_model->insert([
'order_id' => $order_id,
'couponNum' => $this->input->post('coupon_number_1'),
]);
}
if ($total >= 6000) {
if ($this->input->post('coupon_number_2')) {
$this->coupon_approve_model->insert([
'order_id' => $order_id,
'couponNum' => $this->input->post('coupon_number_2'),
]);
}
}
}
//消費者升等
if (!$isDealer) {
if ($old_customer) {
$this->customer_lib->setCustomerID($customer_id);
$this->customer_model->update([
'customer_level_id' => 2,
], ['id' => $customer_id]);
$this->customer_lib->saveLevelChangeHistory(2, 1);
} elseif ($customer_id) {
$this->customer_lib->setCustomerID($customer_id);
$customer_level_id = $this->customer_lib->upgradeLevel();
if ($customer_level_id) {
if ($customer_level_id == 1) {
redirect(base_url('/customer/upgrade/' . $customer_id));
} else {
if ($customer_level_id == 2) {
$this->customer_model->update([
'customer_level_id' => $customer_level_id,
], ['id' => $customer_id]);
$this->customer_lib->saveLevelChangeHistory(2, 1);
$this->session->set_userdata(array('msg' => '已成為春水綠卡會員'));
} elseif ($customer_level_id == 3) {
$this->customer_lib->saveLevelChangeHistory(3, 1);
$this->session->set_userdata(array('msg' => '已成為曜石黑卡會員'));
}
}
}
}
}
//其他門市出貨
if ($this->input->post('payment_type') == 5) {
$order = $this->order_model
->where('buyer_type', 'customer')
->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
->get($order_id);
if ($order) {
$this->load->model('purchase_model');
$this->load->model('purchase_item_model');
$shipout_retailer_id = $this->input->post('shipout_retailer_id');
$discount = $shipout_retailers[$shipout_retailer_id]['discount'];
$purchaseSerialNum = $this->purchase_model->getNextPurchaseSerialNum();
$purchase_id = $this->purchase_model->insert([
'retailer_id' => $this->dealer['retailer_id'],
'retailer_address' => $this->dealer['address'],
'shipout_retailer_id' => $shipout_retailer_id,
'shipin_retailer_id' => $this->dealer['retailer_id'],
'shipin_address' => $this->dealer['address'],
'serialNum' => $purchaseSerialNum,
'purchaseNum' => date('Ym') . $purchaseSerialNum,
'dealer_id' => $this->dealer['id'],
]);
$subtotal = 0;
$total = 0;
foreach ($order['items'] as $item) {
$qty = $item['qty'];
$price = $item['product']['pdCash'];
$this->purchase_item_model->insert([
'purchase_id' => $purchase_id,
'product_id' => $item['product_id'],
'price' => $price,
'qty' => $qty,
'subtotal' => $price * $qty,
'discount' => $discount,
'total' => round($price * $qty * $discount / 100),
]);
$subtotal += $price * $qty;
$total += round($price * $qty * $discount / 100);
}
$this->purchase_model->update([
'isMatchBox' => 1,
'subtotal' => $subtotal,
'total' => $total,
], ['id' => $purchase_id]);
$this->payment_model->insert([
'pay_type' => 'purchase',
'pay_id' => $purchase_id,
'paid_retailer_id' => $this->dealer['retailer_id'],
'received_retailer_id' => $shipout_retailer_id,
'price' => $total,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
'active' => 0,
]);
//新增A店買B店取貨之紀錄
$this->order_transfer_model->insert([
'order_id' => $order_id,
'purchase_id' => $purchase_id,
'retailer_id' => $this->dealer['retailer_id'],
'shipout_retailer_id' => $shipout_retailer_id,
'dealer_id' => $this->dealer['id'],
]);
}
}
if ($_POST['submit_recommend']) {
redirect(base_url('/recommend/add'));
} elseif ($customer_id) {
redirect(base_url('/customer/consumer/' . $customer_id));
} else {
redirect(base_url('/consumer/overview'));
}
}
}
if ($old_customer) {
$title = '舊有會員轉換';
} elseif ($customer) {
$title = '新增消費紀錄';
} else {
$title = '新增新消費者紀錄';
}
$data = [
'isOld' => $old_customer,
'headline' => $title,
'customer' => $customer,
'member_discount' => $member_discount,
'promotes' => $promotes,
'products' => $products,
'combos' => $combos,
'free_packages' => $free_packages,
'payment_type' => $this->payment_type,
'shipout_retailers' => $shipout_retailers,
'staff_max_amount' => $staff_max_amount,
'title' => $title,
'view' => 'consumer/add',
];
$this->_preload($data);
}
public function check_qty($i, $params)
{
$params = json_decode($params, true);
$products = (array)$params['products'];
$combos = (array)$params['combos'];
$packages = (array)$params['packages'];
$items = (array)$params['items'];
$expired_dates = (array)$params['expired_dates'];
$combo_items = (array)$params['combo_items'];
$package_items = (array)$params['package_items'];
$payment_type = (int)$params['payment_type'];
$isShipped = true;
if (in_array($payment_type, [4, 5])) {
$isShipped = false;
}
if (empty($params['gift_items'])) {
$gift_items = [];
$promotes = [];
$promote_id = null;
} else {
$gift_items = (array)$params['gift_items'];
$promotes = (array)$params['promotes'];
$promote_id = (int)$params['promote_id'];
}
$error = '';
$selected_products = [];
if ($combo_items) {
foreach ($combo_items as $combo_id => $item) {
if (!isset($combos[$combo_id])) {
$error = '輸入的組合產品有誤';
break;
}
$item['qty'] = (int)$item['qty'];
if ($item['qty'] === false) {
$error = '輸入的組合產品數量有誤';
break;
} elseif ($this->dealer['hasStock'] && $isShipped && $item['qty'] > $combos[$combo_id]['stock']) {
$error = '輸入的組合產品數量超過庫存上限';
break;
}
foreach ($combos[$combo_id]['items'] as $k => $citem) {
$selected_products = $this->calcProductQty($selected_products, $citem['product_id'], $citem['qty'] * $item['qty']);
}
}
}
if (!$error && $package_items) {
foreach ($package_items as $product_id => $item) {
if (!isset($packages[$product_id])) {
$error = '輸入的免費包裝商品有誤';
break;
}
$item['qty'] = (int)$item['qty'];
if ($item['qty'] === false) {
$error = '輸入的免費包裝商品數量有誤';
break;
}
$selected_products = $this->calcProductQty($selected_products, $product_id, $item['qty']);
}
}
if (!$error && $promote_id && isset($promotes[$promote_id])) {
$hasGift = false;
foreach ($promotes[$promote_id]['methods'] as $method) {
if ($method['promote_type_id'] == 3) {
$options = $method['options'];
if (!empty($options['single'])) { //擇一贈品
if ($gift_items && !empty($gift_items[$method['id']])) {
$pitem = explode('-', $gift_items[$method['id']]);
}
}
foreach ($method['items'] as $item) {
if (empty($options['single']) || (!empty($pitem[0]) && !empty($pitem[1]) && $item['type'] == $pitem[0] && $item['id'] == $pitem[1])) {
if ($item['type'] == 'product') {
$selected_products = $this->calcProductQty($selected_products, $item['id'], $item['qty']);
} elseif ($item['type'] == 'combo') {
if (!empty($combos[$item['id']])) {
foreach ($combos[$item['id']]['items'] as $k => $citem) {
$selected_products = $this->calcProductQty($selected_products, $citem['product_id'], $citem['qty']);
}
} else {
$error = '贈品中的組合商品有誤';
}
}
$hasGift = true;
}
}
}
}
if (!$hasGift) {
$error = '贈品選擇錯誤';
}
}
if (!$error && $items) {
foreach ($items as $product_id => $item) {
if (!isset($products[$product_id])) {
$error = '輸入的貨品有誤';
break;
}
$item['qty'] = (int)$item['qty'];
if ($item['qty'] === false) {
$error = '輸入的貨品數量有誤';
break;
}
$selected_products = $this->calcProductQty($selected_products, $product_id, $item['qty']);
}
}
if (!$error) {
if (!$selected_products) {
$error = '您尚未選購商品';
}
}
if (!$error && $this->dealer['hasStock'] && $isShipped) {
foreach ($selected_products as $product_id => $qty) {
if (isset($expired_dates[$product_id])) {
if (count($expired_dates[$product_id]) == $qty) {
$expired_at_data = [];
foreach ($expired_dates[$product_id] as $expired_at) {
if (!isset($expired_at_data[$expired_at])) {
$expired_at_data[$expired_at] = 0;
}
$expired_at_data[$expired_at]++;
}
foreach ($expired_at_data as $expired_at => $q) {
if ($expired_at) {
$this->stock_model
->where('expired_at', $expired_at)
->where('expired_at', '>=', date('Y-m-d'));
} else {
$this->stock_model->where('expired_at IS NULL', null, null, false, false, true);
}
$stock = $this->stock_model
->where('product_id', $product_id)
->where('retailer_id', $this->dealer['retailer_id'])
->where('stock', '>=', $q)
->get();
if (!$stock) {
$error = '輸入的商品有效期限不符或不足';
break;
}
}
} else {
$error = '商品數量與輸入的商品有效期限數量不符';
break;
}
} else {
$error = '您尚未填寫商品有效期限';
break;
}
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_qty', $error);
return false;
}
}
protected function calcProductQty($selected_products, $product_id, $qty)
{
if (!isset($selected_products[$product_id])) {
$selected_products[$product_id] = 0;
}
$selected_products[$product_id] += $qty;
return $selected_products;
}
public function check_promote($promote_id, $params)
{
$params = json_decode($params, true);
$isDealer = $params['isDealer'];
$promotes = $params['promotes'];
foreach ($promotes as $promote) {
if ($promote['id'] == $promote_id) {
switch ($promote['customer_type']) {
case 3:
if ($isDealer) {
return true;
}
break;
default:
return true;
break;
}
}
}
$this->form_validation->set_message('check_promote', '優惠活動選擇錯誤');
return false;
}
//檢查核發優惠券是否重複
public function check_coupon($couponNum)
{
if ($couponNum) {
$this->load->model('coupon_approve_model');
$coupon_count = $this->coupon_approve_model
->where('couponNum', $couponNum)
->count_rows();
if ($coupon_count) {
$this->form_validation->set_message('check_coupon', '折價券編號重複');
return false;
}
}
return true;
}
public function edit($order_id)
{
$order = $this->order_model
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->with_shipment('fields:ctName')
->get($order_id);
if (!$order_id || !$order) {
show_error('查無消費紀錄');
}
if ($this->input->post()) {
$this->form_validation->set_rules('created_at', '訂單日期', 'required|valid_date');
if ($this->form_validation->run() !== FALSE) {
$this->order_model->update([
'created_at' => $this->input->post('created_at'),
], ['id' => $order_id]);
redirect(base_url('/consumer/overview'));
}
}
$data = [
'order' => $order,
'title' => '編輯消費紀錄',
'view' => 'consumer/edit',
];
$this->_preload($data);
}
public function cancel($order_id)
{
$order = $this->order_model
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->with_shipment('fields:ctName')
->get($order_id);
if (!$order_id || !$order) {
show_error('查無消費紀錄');
}
$this->order_model->delete($order_id);
//刪除付款
$payment = $this->payment_model
->where('pay_type', 'order')
->where('pay_id', $order_id)
->where('received_retailer_id', $this->dealer['retailer_id'])
->get();
if ($payment) {
$this->payment_model->delete($payment['id']);
}
//刪除出貨
$shipment = $this->shipment_model
->where('ship_type', 'consumer')
->where('ship_id', $order_id)
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get();
if ($shipment) {
//出貨扣庫恢復
$this->stock_lib->shipout_rollback($shipment['id']);
$this->shipment_model->delete($shipment['id']);
$this->order_model->update(['isShipped' => 0, 'dealer_id' => $this->dealer['id']], ['id' => $order_id]);
}
redirect(base_url('/consumer/overview'));
}
public function recover($order_id)
{
$order = $this->order_model
->only_trashed()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->with_shipment('fields:ctName')
->get($order_id);
if (!$order_id || !$order) {
show_error('查無消費紀錄');
}
$this->order_model->delete($order_id);
//刪除付款恢復
$payment = $this->payment_model
->only_trashed()
->where('pay_type', 'order')
->where('pay_id', $order_id)
->where('received_retailer_id', $this->dealer['retailer_id'])
->get();
if ($payment) {
$this->payment_model->restore($payment['id']);
}
//刪除出貨恢復
$shipment = $this->shipment_model
->only_trashed()
->where('ship_type', 'consumer')
->where('ship_id', $order_id)
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get();
if ($shipment) {
$this->shipment_model->restore($shipment['id']);
$this->stock_lib->shipout_confirm($shipment['id']);
$this->order_model->update(['isShipped' => 0, 'dealer_id' => $this->dealer['id']], ['id' => $order_id]);
}
$this->order_model->update(
[
'dealer_id' => $this->dealer['id'],
'deleted_at' => null
], ['id' => $order_id]);
redirect(base_url('/consumer/trashed'));
}
public function payAtShipped()
{
$total_orders_count = $this->order_model
->with_payments(['where' => "type_id=4"])//貨到付款
->with_shipments()
->with_returns()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->count_rows();
$orders = $this->order_model
->with_payments(['where' => "type_id=4"])
->with_shipments()
->with_returns()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->order_by('id', 'desc')
->paginate(20, $total_orders_count);
//權限設定
$authority = array();
if ($this->authentic->authority('consumer', 'detail')) {
$authority['detail'] = true;
}
if ($this->authentic->authority('consumer', 'shipping')) {
$authority['shipping'] = true;
}
if ($this->authentic->authority('consumer', 'paying')) {
$authority['paying'] = true;
}
if ($this->authentic->authority('consumer', 'reject')) {
$authority['reject'] = true;
}
if ($this->authentic->authority('consumer', 'orderReturn')) {
$authority['orderReturn'] = true;
}
$data = [
'orders' => $orders,
'pagination' => $this->order_model->all_pages,
'authority' => $authority,
'title' => '貨到付款管理',
'view' => 'consumer/pay_at_shipped',
];
$this->_preload($data);
}
public function shipping($order_id)
{
$order = $this->order_model
->with_items()
->with_shipments()
->with_recipient()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($order_id);
if (!$order) {
show_error('查無訂單資料');
}
if (!empty($order['shipments'])) {
$last_shipment = end($order['shipments']);
if ($last_shipment['isConfirmed']) {
show_error('此訂單已出貨');
} elseif ($last_shipment['isConfirmed'] === '0') { //拒絕收貨
if (!empty($order['returns'])) {
show_error('此訂單已退貨');
}
}
}
$this->load->model('order_item_model');
$items = $this->order_item_model
->with_product()
->where('order_id', $order_id)
->get_all();
if (!$items) {
show_error('訂單無商品資料');
} else {
$products = [];
foreach ($items as $item) {
if (!isset($products[$item['product_id']])) {
$stocks = $this->stock_model
->where('product_id', $item['product_id'])
->where('retailer_id', $this->dealer['retailer_id'])
->where('stock', '>', 0)
->group_start()
->where('expired_at', '>=', date('Y-m-d'), true)
->where('expired_at IS NULL', null, null, true, false, true)
->group_end()
->order_by('ISNULL(expired_at)', 'asc')
->order_by('expired_at', 'asc')
->get_all();
$products[$item['product_id']] = [
'name' => $item['product']['pdName'] . $item['product']['intro2'],
'qty' => 0,
'stocks' => $stocks,
];
}
$products[$item['product_id']]['qty'] += $item['qty'];
}
}
$error = [];
if ($this->input->post()) {
$this->form_validation->set_rules('fare', '手續費', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('freight', '運費', 'required|integer|greater_than_equal_to[0]');
$check_expired_options = [
'products' => $products,
'items' => $this->input->post('items'),
];
$this->form_validation->set_rules('items', '出貨數量', 'callback_check_shipping_qty[' . json_encode($check_expired_options) . ']');
if ($this->form_validation->run() !== FALSE) {
$product_verify = null;
$fare_verify = null;
$shipment_verify = null;
if (!empty($_FILES)) {
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
if ($_FILES['product_verify'] && $_FILES['product_verify']['size']) {
if ($this->upload->do_upload('product_verify')) {
$upload_data = $this->upload->data();
$product_verify = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
}
if ($_FILES['fare_verify'] && $_FILES['fare_verify']['size']) {
if ($this->upload->do_upload('fare_verify')) {
$upload_data = $this->upload->data();
$fare_verify = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
}
if ($_FILES['shipment_verify'] && $_FILES['shipment_verify']['size']) {
if ($this->upload->do_upload('shipment_verify')) {
$upload_data = $this->upload->data();
$shipment_verify = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
}
}
$shipment_id = $this->shipment_model->insert([
'ship_type' => 'consumer',
'ship_id' => $order_id,
'shipout_retailer_id' => $this->dealer['retailer_id'],
'shipin_retailer_id' => null,
'eta_at' => date('Y-m-d'),
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'product_verify' => $product_verify,
'fare_verify' => $fare_verify,
'shipment_verify' => $shipment_verify,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
foreach ($order['items'] as $item) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
}
//紀錄產品有效期限
$items = (array)$this->input->post('items');
foreach ($items as $product_id => $expired_data) {
foreach ($expired_data as $expired_at => $qty) {
if ($qty > 0) {
$this->shipment_expiration_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $qty,
]);
}
}
}
//出貨扣庫
$this->stock_lib->shipout_confirm($shipment_id);
$this->order_model->update(['isShipped' => 1, 'dealer_id' => $this->dealer['id']], ['id' => $order_id]);
//運費
$this->load->model('expense_model');
$fare = $this->input->post('fare');
$freight = $this->input->post('freight');
if ($fare > 0) {
$this->expense_model->insert([
'retailer_id' => $this->dealer['retailer_id'],
'event_type' => 'shipment',
'event_id' => $shipment_id,
'expense_type' => 'fare',
'price' => $fare,
'dealer_id' => $this->dealer['id'],
]);
}
if ($freight > 0) {
$this->expense_model->insert([
'retailer_id' => $this->dealer['retailer_id'],
'event_type' => 'shipment',
'event_id' => $shipment_id,
'expense_type' => 'freight',
'price' => $freight,
'dealer_id' => $this->dealer['id'],
]);
}
redirect(base_url('/consumer/payAtShipped/'));
}
}
$data = [
'order' => $order,
'products' => $products,
'error' => $error,
'title' => '貨到付款確認寄出',
'view' => 'consumer/shipping',
];
$this->_preload($data);
}
public function check_shipping_qty($i, $params)
{
$params = json_decode($params, true);
$products = (array)$params['products'];
$items = (array)$params['items'];
$error = '';
if (!$items) {
$error = '無輸入任何商品';
} else {
foreach ($items as $product_id => $expired_data) {
if (!isset($products[$product_id])) {
$error = '輸入的商品有誤';
break;
}
$shipping_qty = 0;
foreach ($expired_data as $expired_at => $qty) {
if ($qty > 0) {
$match_stock = false;
foreach ($products[$product_id]['stocks'] as $stock) {
if ((is_null($stock['expired_at']) && empty($expired_at)) || $stock['expired_at'] == $expired_at) {
if ($stock['stock'] < $qty) {
$error = '輸入的商品出貨數量大於有效日之庫存';
break 3;
}
$match_stock = true;
}
}
if (!$match_stock) {
$error = '輸入的商品庫存到期日有誤';
break 2;
}
$shipping_qty += $qty;
}
}
if ($products[$product_id]['qty'] != $shipping_qty) {
$error = '輸入的商品訂購數量與出貨總量不符';
break;
}
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_shipping_qty', $error);
return false;
}
}
public function paying($order_id)
{
$order = $this->order_model
->with_payments(['where' => "type_id=4"])
->with_shipments()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($order_id);
if (!$order) {
show_error('查無訂單資料');
}
if (empty($order['shipments'])) {
show_error('查無訂單資料');
}
$last_shipment = end($order['shipments']);
$last_payment = end($order['payments']);
if (!is_null($last_shipment['isConfirmed'])) {
show_error('此訂單已收款作業');
}
if ($this->input->post()) {
$this->shipment_model->update(['isConfirmed' => 1], ['id' => $last_shipment['id']]);
$this->payment_model->update(['active' => 1, 'isConfirmed' => 1], ['id' => $last_payment['id']]);
$this->order_model->update(['isShipped' => 1, 'isPaid' => 1], ['id' => $order_id]);
$this->load->model('confirm_model');
$this->confirm_model->insert([
'confirm_type' => 'shipment',
'confirm_id' => $last_shipment['id'],
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => 1,
'dealer_id' => $this->dealer['id'],
]);
redirect(base_url('/consumer/payAtShipped/'));
}
$data = [
'order' => $order,
'title' => '貨到付款收款作業',
'view' => 'consumer/paying',
];
$this->_preload($data);
}
public function reject($order_id)
{
$order = $this->order_model
->with_payments(['where' => "type_id=4"])
->with_shipments()
->with_items()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($order_id);
if (!$order) {
show_error('查無訂單資料');
}
if (empty($order['shipments'])) {
show_error('查無訂單資料');
}
$last_shipment = end($order['shipments']);
$last_payment = end($order['payments']);
if (!is_null($last_shipment['isConfirmed'])) {
show_error('此訂單已收款作業');
}
if ($this->input->post()) {
$this->form_validation->set_rules('reason', '拒收原因', 'required|max_length[200]');
if ($_POST['reason'] == '其他') {
$this->form_validation->set_rules('reason_text', '其他拒收原因', 'required|max_length[200]');
}
$this->form_validation->set_rules('reject_type', '貨品處理方式', 'required|integer|in_list[1,2]');
if ($this->form_validation->run() !== FALSE) {
$this->shipment_model->update(['isConfirmed' => 0], ['id' => $last_shipment['id']]);
$this->payment_model->update(['isConfirmed' => 0], ['id' => $last_payment['id']]);
if ($this->input->post('reject_type') == 2) { //退貨
$order_return_id = $this->order_return_model->insert([
'order_id' => $order_id,
'isReturn' => 0,
'dealer_id' => $this->dealer['id'],
]);
foreach ($order['items'] as $item) {
$this->order_return_item_model->insert([
'order_return_id' => $order_return_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
'price' => $item['price'],
'discount' => $item['discount'],
'subPrice' => $item['subPrice'],
]);
}
} elseif ($this->input->post('reject_type') == 1) { //重新寄出貨品
$this->stock_lib->shipout_rollback($last_shipment['id']);
$this->shipment_expiration_model
->where('shipment_id', $last_shipment['id'])
->delete();
}
//運送確認
if ($this->input->post('reason')) {
if ($this->input->post('reason') == '其他') {
$reason = $this->input->post('reason_text');
} else {
$reason = $this->input->post('reason');
}
} else {
$reason = null;
}
$this->load->model('confirm_model');
$this->confirm_model->insert([
'confirm_type' => 'shipment',
'confirm_id' => $last_shipment['id'],
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => 0,
'memo' => $reason,
'dealer_id' => $this->dealer['id'],
]);
redirect(base_url('/consumer/payAtShipped/'));
}
}
$data = [
'order' => $order,
'title' => '貨到付款客戶拒收',
'view' => 'consumer/reject',
];
$this->_preload($data);
}
public function orderReturn($order_id)
{
$order = $this->order_model
->with_shipments()
->with_returns()
->where('buyer_type', 'customer')
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($order_id);
if (!$order) {
show_error('查無訂單資料');
}
if (empty($order['shipments'])) {
show_error('查無訂單資料');
}
$last_shipment = end($order['shipments']);
if ($last_shipment['isConfirmed'] || is_null($last_shipment['isConfirmed'])) {
show_error('此訂單已出貨');
} else { //拒絕收貨
if (empty($order['returns'])) {
show_error('此訂單重新出貨');
}
}
$last_return = end($order['returns']);
$order_return_items = $this->order_return_item_model
->with_product()
->where('order_return_id', $last_return['id'])
->get_all();
if ($this->input->post()) {
$this->form_validation->set_rules('fare', '手續費', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('freight', '運費', 'required|integer|greater_than_equal_to[0]');
if ($this->form_validation->run() !== FALSE) {
$this->order_return_model->update(['isReturn' => 1], ['id' => $last_return['id']]);
//出貨扣庫恢復
$this->stock_lib->shipout_rollback($last_shipment['id']);
$this->shipment_expiration_model->where('pay_type', 'purchase')
->where('shipment_id', $last_shipment['id'])
->delete();
//運費
$this->load->model('expense_model');
$fare = $this->input->post('fare');
$freight = $this->input->post('freight');
if ($fare > 0) {
$this->expense_model->insert([
'retailer_id' => $this->dealer['retailer_id'],
'event_type' => 'order_return',
'event_id' => $last_return['id'],
'expense_type' => 'fare',
'price' => $fare,
'dealer_id' => $this->dealer['id'],
]);
}
if ($freight > 0) {
$this->expense_model->insert([
'retailer_id' => $this->dealer['retailer_id'],
'event_type' => 'order_return',
'event_id' => $last_return['id'],
'expense_type' => 'freight',
'price' => $freight,
'dealer_id' => $this->dealer['id'],
]);
}
redirect(base_url('/consumer/payAtShipped/'));
}
}
$data = [
'order' => $order,
'items' => $order_return_items,
'title' => '貨到付款退貨作業',
'view' => 'consumer/order-return',
];
$this->_preload($data);
}
public function transfer()
{
$total_transfers_count = $this->order_transfer_model
->group_start()
->where('retailer_id', $this->dealer['retailer_id'], null, true)
->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
->group_end()
->count_rows();
$transfers = $this->order_transfer_model
->with_order(['with' => ['relation' => 'contact']])
->with_retailer()
->with_shipout_retailer()
->group_start()
->where('retailer_id', $this->dealer['retailer_id'], null, true)
->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
->group_end()
->order_by($this->order_transfer_model->get_table_name() . '.id', 'desc')
->paginate(20, $total_transfers_count);
//權限設定
$authority = array();
if ($this->authentic->authority('consumer', 'transfer_record')) {
$authority['transfer_record'] = true;
}
if ($this->authentic->authority('consumer', 'transfer_delivery')) {
$authority['transfer_delivery'] = true;
}
if ($this->authentic->authority('consumer', 'detail')) {
$authority['detail'] = true;
}
$data = [
'transfers' => $transfers,
'pagination' => $this->order_transfer_model->all_pages,
'authority' => $authority,
'title' => 'A店買B店取貨之紀錄',
'view' => 'consumer/transfer',
];
$this->_preload($data);
}
public function transfer_record($order_transfer_id)
{
$transfer = $this->order_transfer_model
->group_start()
->where('retailer_id', $this->dealer['retailer_id'], null, true)
->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
->group_end()
->get($order_transfer_id);
if (!$order_transfer_id || !$transfer) {
show_error('查無A店買B店取貨之紀錄');
}
if ($transfer['isRecorded']) {
show_error('已開立取貨單');
}
$this->order_transfer_model->update([
'isRecorded' => 1
], ['id' => $order_transfer_id]);
redirect(base_url('/consumer/transfer/'));
}
public function transfer_delivery($order_transfer_id)
{
$transfer = $this->order_transfer_model
->with_order([
'with' => [
['relation' => 'items', 'with' => ['relation' => 'product']],
['relation' => 'contact'],
]
])
->with_purchase(['with' => ['relation' => 'items']])
->group_start()
->where('retailer_id', $this->dealer['retailer_id'], null, true)
->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
->group_end()
->get($order_transfer_id);
if (!$order_transfer_id || !$transfer) {
show_error('查無A店買B店取貨之紀錄');
}
if (!$transfer['isRecorded']) {
show_error('未開立取貨單');
}
if ($transfer['isDeliveried']) {
show_error('已確認取貨');
}
$order_id = $transfer['order_id'];
$purchase_id = $transfer['purchase_id'];
$shipout_retailer_id = $transfer['shipout_retailer_id'];
$retailer_id = $transfer['retailer_id'];
$today = date('Y-m-d');
$products = [];
foreach ($transfer['order']['items'] as $item) {
if (!isset($products[$item['product_id']])) {
$stocks = $this->stock_model
->where('product_id', $item['product_id'])
->where('retailer_id', $shipout_retailer_id)
->where('stock', '>', 0)
->group_start()
->where('expired_at', '>=', date('Y-m-d'), true)
->where('expired_at IS NULL', null, null, true, false, true)
->group_end()
->order_by('ISNULL(expired_at)', 'asc')
->order_by('expired_at', 'asc')
->get_all();
$products[$item['product_id']] = [
'name' => $item['product']['pdName'] . $item['product']['intro2'],
'qty' => 0,
'stocks' => $stocks,
];
}
$products[$item['product_id']]['qty'] += $item['qty'];
}
if ($this->input->post()) {
$check_expired_options = [
'products' => $products,
'items' => $this->input->post('items'),
];
$this->form_validation->set_rules('items', '出貨數量', 'callback_check_shipping_qty[' . json_encode($check_expired_options) . ']');
if ($this->form_validation->run() !== FALSE) {
//確定出貨單
$this->load->model('confirm_model');
$confirm = $this->confirm_model
->where('confirm_type', 'purchase')
->where('confirm_id', $purchase_id)
->get();
if (!$confirm) {
$this->confirm_model->insert([
'confirm_type' => 'purchase',
'confirm_id' => $purchase_id,
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => 1,
'dealer_id' => $this->dealer['id'],
]);
}
$this->purchase_model->update(['isConfirmed' => 1], ['id' => $purchase_id]);
//進貨單出貨,不扣庫
$shipment_id = $this->shipment_model->insert([
'ship_type' => 'purchase',
'ship_id' => $purchase_id,
'shipout_retailer_id' => $shipout_retailer_id,
'shipin_retailer_id' => $retailer_id,
'eta_at' => $today,
'memo' => null,
'isConfirmed' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->update(['isShipped' => 1, 'shipped_at' => $today], ['id' => $purchase_id]);
foreach ($transfer['purchase']['items'] as $item) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
}
//收貨作業確認
$this->confirm_model->insert([
'confirm_type' => 'shipment',
'confirm_id' => $shipment_id,
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => 1,
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->checkCorrect($purchase_id);
//消費者出貨單
$shipment_id = $this->shipment_model->insert([
'ship_type' => 'consumer',
'ship_id' => $order_id,
'shipout_retailer_id' => $shipout_retailer_id,
'shipin_retailer_id' => null,
'eta_at' => $today,
'memo' => null,
'isConfirmed' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
$items = $transfer['order']['items'];
foreach ($items as $item) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
}
//紀錄產品有效期限
$items = (array)$this->input->post('items');
foreach ($items as $product_id => $expired_data) {
foreach ($expired_data as $expired_at => $qty) {
if ($qty > 0) {
$this->shipment_expiration_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $qty,
]);
}
}
}
//出貨扣庫
$this->stock_lib->shipout_confirm($shipment_id);
$this->order_transfer_model->update([
'isDeliveried' => 1
], ['id' => $order_transfer_id]);
redirect(base_url('/consumer/transfer/'));
}
}
$data = [
'transfer' => $transfer,
'products' => $products,
'title' => 'A店買B店取貨之確認取貨',
'view' => 'consumer/transfer_delivery',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/capital/retailer/overview.php
<div class="container">
<h1 class="mb-4">單位列表
<?php if (!empty($authority['add'])){ ?>
<a href="<?= base_url('/capital_retailer/add') ?>" class="btn btn-success float-right"><i class="far fa-plus-square"></i> 新增單位</a>
<?php } ?>
</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">單位類型</th>
<th class="text-center">名稱</th>
<th class="text-center">代表人姓名</th>
<th class="text-center">聯絡電話1</th>
<th class="text-center">聯絡電話2</th>
<th class="text-center">送貨地址</th>
<th class="text-center">管理庫存</th>
<th class="text-center">總倉庫存</th>
<th class="text-center">散裝進貨資格</th>
<th></th>
</tr>
<?php
if ($retailers) {
foreach ($retailers as $retailer) {
?>
<tr>
<td class="text-center"><?= (empty($retailer['level']) ? $retailer['role']['title'] : $retailer['level']['type']['title'] . ' ' . $retailer['level']['code']) ?></td>
<td class="text-center"><?= $retailer['company'] ?></td>
<td class="text-center"><?= empty($retailer['contact_dealer']) ? '' : $retailer['contact_dealer']['name'] ?></td>
<td class="text-center"><?= $retailer['phone'] ?></td>
<td class="text-center"><?= $retailer['altPhone'] ?></td>
<td class="text-center"><?= $retailer['address'] ?></td>
<td class="text-center"><?= yesno($retailer['hasStock']) ?></td>
<td class="text-center"><?= yesno($retailer['totalStock']) ?></td>
<td class="text-center"><?= yesno($retailer['isAllowBulk']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['edit'])){ ?>
<a class="btn btn-warning btn-sm" href="<?= base_url('/capital_retailer/edit/' . $retailer['id']) ?>">編輯</a>
<?php } ?>
<button type="button" class="btn btn-warning btn-sm dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<?php if (!empty($authority['dealer'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_dealer/overview/' . $retailer['id']) ?>">人員列表</a>
<?php } ?>
<?php if (!empty($authority['qualification'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_retailer_qualification/overview/' . $retailer['id']) ?>">經銷拓展資格</a>
<?php } ?>
<?php if (!empty($authority['shipout'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_relationship_shipout/overview/' . $retailer['id']) ?>">出貨關係單位</a>
<?php } ?>
<?php if (!empty($authority['shipin'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_relationship_shipin/overview/' . $retailer['id']) ?>">收貨關係單位</a>
<?php } ?>
<?php if (!empty($authority['invoice'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_relationship_invoice/overview/' . $retailer['id']) ?>">發票關係單位</a>
<?php } ?>
<?php if (!empty($authority['invoice_send'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_relationship_invoice_send/overview/' . $retailer['id']) ?>">發票寄送關係單位</a>
<?php } ?>
<?php if (!empty($authority['supervisor'])){ ?>
<a class="dropdown-item" href="<?= base_url('/capital_relationship_visor/overview/' . $retailer['id']) ?>">輔銷關係單位</a>
<?php } ?>
<?php if (!empty($authority['cancel']) && !$retailer['isLocked']){ ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"
data-href="<?= base_url('/capital_retailer/cancel/' . $retailer['id']) ?>"
data-toggle="modal" data-target="#confirm-delete"><i class="fas fa-trash"></i> 刪除</a>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="7" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal" id="confirm-delete" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-trash"></i> 刪除確認</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>是否確定刪除?</p>
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
<a href="" class="btn btn-danger btn-confirm"><i class="fas fa-trash"></i> 刪除</a>
</div>
</div>
</div>
</div>
<script>
$().ready(function(){
$('#confirm-delete').on('show.bs.modal', function(e){
$(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
});
});
</script><file_sep>/application/views/coupon/confirm.php
<div class="container">
<h1 class="mb-4">折價券審核</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">單位名稱</th>
<th class="text-center">年分/月份</th>
<th class="text-center">領用張數</th>
<th></th>
</tr>
<?php
if ($confirms) {
foreach ($confirms as $confirm) {
?>
<tr>
<td class="text-center"><?= $confirm['coupon']['retailer']['company'] ?></td>
<td class="text-center"><?= date('Y年m月', strtotime($confirm['coupon']['coupon_month'])) ?></td>
<td class="text-center"><?= $confirm['coupon']['receive_qty'] ?></td>
<td class="text-center">
<div class="btn-group">
<?php if (!empty($authority['approved'])){ ?>
<a class="btn btn-primary btn-sm"
href="<?= base_url('/coupon/approved/' . $confirm['id']) ?>">
<i class="far fa-square"></i> 審核
</a>
<?php } ?>
</div>
</td>
<?php
}
}
?>
</table>
</div><file_sep>/application/views/recommend/add.php
<div class="container">
<h1 class="mb-4">來賓推薦作業</h1>
<?php if (!$template_id){ ?>
<h4 class="mb-4 text-center">選取推薦函<span class="text-danger">(行銷必須之作業)</span></h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">編號</th>
<th class="text-left">內容</th>
<th></th>
</tr>
<?php
if ($templates) {
foreach ($templates as $template) {
?>
<tr>
<td class="text-center">#<?= $template['id'] ?></td>
<td class="text-left"><?= nl2br($template['content']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<a class="btn btn-success" href="<?= base_url('/recommend/add/' . $template['id']) ?>">選取推薦函內容</a>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="3" class="text-center">查無資料</td>
</tr>
<?php
}
?>
<tr>
<td colspan="3" class="text-center">
<a class="btn btn-success" href="<?= base_url('/recommend/add/true') ?>">略過</a>
</td>
</tr>
</table>
<?= $pagination ?>
<?php } else { ?>
<form method="post" id="recommend_form" enctype="multipart/form-data">
<div class="card mb-4">
<div class="card-header">推薦函/ (來賓必須簽名)
<a href="<?=base_url('/recommend/add')?>" class="btn btn-success btn-sm float-right">重新選擇推薦函</a>
</div>
<div class="card-body">
<div class="mb-4"><?=empty($template['content']) ? '' : nl2br($template['content'])?></div>
<div class="font-weight-bold border-bottom pb-5" style="height: 100px;">請於此範圍內簽上姓名及日期</div>
<p><small>本人簽名同意一個橄欖將本推薦函及相關照片用於其行銷作業上</small></p>
<div class="form-group">
<a id="btn-print" href="<?=base_url('/recommend/print_recommend/' . $template_id)?>" target="_blank" data-printed="0" class="btn btn-light mr-4">檢視推薦函後列印<br />尚未列印</a>
</div>
<div class="form-group">
<input type="checkbox" id="agree" required>
<label class="form-check-label" for="agree">推薦函簽名完成(同時親筆抄寫簽名一份為佳)</label>
</div>
<div class="form-group">
<label class="form-check-label">已將簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾</label>
<input type="file" class="form-control-file" id="picture1" name="picture1" required />
</div>
</div>
</div>
<div class="card mb-4">
<div class="card-header">推薦照片</div>
<div class="card-body">
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="radio" name="hasPicture2" id="hasPicture2Radios1" value="1" required>
<label class="form-check-label" for="hasPicture2Radios1">
有來賓推薦照片
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="hasPicture2" id="hasPicture2Radios2" value="0">
<label class="form-check-label" for="hasPicture2Radios2">
無來賓推薦照片
</label>
</div>
</div>
<div class="form-group">
<label class="form-check-label">將來賓推薦之照片傳入電腦中之指定資料夾</label>
<input type="file" class="form-control-file" id="picture2" name="picture2" />
</div>
</div>
</div>
<div class="form-group d-flex justify-content-end">
<input type="submit" name="temp_add" class="btn btn-success mr-2" value="暫存 / 先做別的"/>
<button class="btn btn-success">推薦作業完成</button>
</div>
</form>
<?php } ?>
</div>
<script>
$(document).ready(function () {
$('#btn-print').click(function(){
$(this).html('檢視推薦函後列印<br />已列印');
$(this).data('printed', 1);
});
$('#agree').change(function(e){
e.preventDefault();
var printed = parseInt($('#btn-print').data('printed')) || 0;
if (printed != 1){
alert('請先列印推薦函');
$(this).prop('checked', false);
} else {
$(this).prop('checked', true);
}
});
$("#recommend_form").submit(function (e) {
if ($('#picture1').val() == ''){
alert('請將簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾!');
return false;
}
if ($('input[name="hasPicture2"]').val() == ''){
alert('請確認有無來賓推薦照片!');
return false;
}
if ($('input[name="hasPicture2"]:checked').val() == 1 && $('#picture2').val() == ''){
alert('請將來賓推薦照傳入電腦中之指定資料!');
return false;
}
});
});
</script><file_sep>/application/migrations/002_add_dealer.php
<?php
//經銷商帳號
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_dealer extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'retailer_group_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'account' => [ //代號
'type' => 'VARCHAR',
'constraint' => 10,
],
'password' => [
'type' => 'VARCHAR',
'constraint' => 30,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'gender' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'default' => 1,
],
'isLocked' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_dealers');
}
public function down()
{
$this->dbforge->drop_table('olive_dealers');
}
}<file_sep>/application/views/customer/old.php
<div class="container">
<h1 class="mb-4">未轉換舊有會員資訊
<div class="float-right">
<?php if (!empty($authority['import'])){ ?>
<a href="<?= base_url('/customer/import') ?>" class="btn btn-success"><i class="fas fa-upload"></i> 匯入舊有會員</a>
<?php } ?>
</div>
</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">匯入日期</th>
<th class="text-center">姓名</th>
<th class="text-center">聯絡電話</th>
<th class="text-center">Email</th>
<th class="text-center">地址</th>
<th></th>
</tr>
<?php
if ($customers) {
foreach ($customers as $customer) {
?>
<tr>
<td class="text-center"><?= $customer['created_at'] ?></td>
<td class="text-center"><?= $customer['name'] ?></td>
<td class="text-center"><?= $customer['phone'] ?></td>
<td class="text-center"><?= $customer['email'] ?></td>
<td class="text-center"><?= $customer['address'] ?></td>
<td class="text-center">
<?php if (!empty($authority['old'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/customer/old_detail/' . $customer['id']) ?>">
<i class="fas fa-search"></i> 舊會員資料
</a>
<?php } ?>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="6" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/migrations/018_add_coupon.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_coupon extends CI_Migration
{
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'coupon_month' => [
'type' => 'date',
],
'receive_qty' => [ //領用張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
],
'issue_qty' => [ //發放張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
],
'approve_qty' => [ //核定張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_coupons');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'coupon_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'order_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'couponNum' => [
'type' => 'VARCHAR',
'constraint' => 30,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_coupon_approves');
}
public function down()
{
$this->dbforge->drop_table('olive_coupons');
$this->dbforge->drop_table('olive_coupon_approves');
}
}<file_sep>/application/views/dealer/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">單位資料修改</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>單位名稱</label>
<input name="company" class="form-control" value="<?= set_value('company', $retailer['company']) ?>"/>
</div>
<div class="form-group">
<label>單位抬頭</label>
<input name="invoice_title" class="form-control" value="<?= set_value('invoice_title', $retailer['invoice_title']) ?>"/>
</div>
<div class="form-group">
<label>收款銀行</label>
<input name="bank" class="form-control" value="<?= set_value('bank', $retailer['bank']) ?>" maxlength="100" />
</div>
<div class="form-group">
<label>分行名</label>
<input name="bank_branch" class="form-control" value="<?= set_value('bank_branch', $retailer['bank_branch']) ?>" maxlength="100" />
</div>
<div class="form-group">
<label>收款戶名</label>
<input name="bank_account_title" class="form-control" value="<?= set_value('bank_account_title', $retailer['bank_account_title']) ?>" maxlength="100" />
</div>
<div class="form-group">
<label>收款帳戶</label>
<input name="bank_account" class="form-control" value="<?= set_value('bank_account', $retailer['bank_account']) ?>" maxlength="100" />
</div>
<div class="form-group">
<label>身份證字號/統一編號</label>
<input name="identity" class="form-control"
value="<?= set_value('identity', $retailer['identity']) ?>"/>
</div>
<div class="form-group">
<label>單位代表人</label>
<?php
echo form_dropdown('contact_dealer_id', $dealers, set_value('contact_dealer_id', $retailer['contact_dealer_id']), 'class="form-control"');
?>
</div>
<div class="form-group">
<label>聯絡電話1</label>
<input name="phone" class="form-control"
value="<?= set_value('phone', $retailer['phone']) ?>"/>
</div>
<div class="form-group">
<label>聯絡電話2</label>
<input name="altPhone" class="form-control" value="<?= set_value('altPhone', $retailer['altPhone']) ?>"/>
</div>
<div class="form-group">
<label>聯絡地址</label>
<input name="address" class="form-control" value="<?= set_value('address', $retailer['address']) ?>"/>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div>
<file_sep>/application/migrations/055_update_customer_dealer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_customer_dealer extends CI_Migration {
public function up()
{
$this->dbforge->add_column('olive_customers', [
'isDealer' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'old_customer_id',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_customers', 'isDealer');
}
}<file_sep>/application/models/Order_transfer_model.php
<?php
class Order_transfer_model extends MY_Model
{
public $table = 'olive_order_transfers';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['order'] = array('foreign_model' => 'Order_model', 'foreign_table' => 'olive_orders', 'foreign_key' => 'id', 'local_key' => 'order_id');
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
$this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
}
}
?>
<file_sep>/application/models/Option_model.php
<?php
class Option_model extends MY_Model
{
public $table = 'olive_options';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
}
}
?>
<file_sep>/application/views/customer/active_old.php
<div class="container">
<h1 class="mb-4">會員資料區
<div class="btn-group float-right" role="group">
<button type="button" class="btn btn-success float-right" data-toggle="modal"
data-target="#levelDescriptionModal">會員資格說明</button>
<?php if (!empty($authority['export'])){ ?>
<div class="btn-group" role="group">
<button id="btnGroupDrop1" type="button" class="btn btn-warning dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
匯出
</button>
<div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<a class="dropdown-item" href="<?=base_url('/customer/export')?>">會員資料</a>
<a class="dropdown-item" href="<?=base_url('/customer/export/1')?>">舊有會員資料</a>
</div>
</div>
<?php } ?>
</div>
</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">會員等級</th>
<th class="text-center">姓名</th>
<th class="text-center">聯絡電話</th>
<th class="text-center">Email</th>
<th class="text-center">地址</th>
<th class="text-center"></th>
</tr>
<?php
if ($customers) {
foreach ($customers as $customer) {
?>
<tr>
<td class="text-center"><?= empty($customer['level']) ? '' : $customer['level']['title'] ?></td>
<td class="text-center"><?= $customer['name'] ?></td>
<td class="text-center"><?= $customer['phone'] ?></td>
<td class="text-center"><?= $customer['email'] ?></td>
<td class="text-center"><?= $customer['address'] ?></td>
<td class="text-center">
<?php if (!empty($authority['consumer'])){ ?>
<a class="btn btn-success btn-sm"
href="<?= base_url('/customer/consumer/' . $customer['id']) ?>">
<i class="fas fa-search"></i> 消費紀錄
</a>
<?php } ?>
<?php if (!is_null($customer['old_customer_id']) && !empty($authority['old'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/customer/old_detail/' . $customer['old_customer_id']) ?>">
<i class="fas fa-search"></i> 舊會員資料
</a>
<?php } ?>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="6" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal fade" id="levelDescriptionModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">會員資格說明</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
if ($levels) {
foreach ($levels as $level) {
?>
<div class="form-group">
<h3><?=$level['title']?></h3>
<div>
<?=$level['description']?>
</div>
</div>
<?php
}
}
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div><file_sep>/application/views/capital/stock/overview.php
<div class="container">
<h1 class="mb-4">單位庫存</h1>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">查詢單位</label>
<div class="col-sm-10">
<?php
echo form_dropdown('retailer_id', ['' => ''] + $retailer_selects, set_value('retailer_id', $retailer_id), 'id="retailer_id" class="form-control required"');
?>
</div>
</div>
<?php if ($retailer_id){ ?>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">項次</th>
<th class="text-center">貨品編號</th>
<th class="text-center">貨品名稱</th>
<th class="text-center">正常品數量</th>
<th class="text-center">即期品數量</th>
<th class="text-center">過期品數量</th>
<th class="text-center">未標到期日數量</th>
<?php if (!empty($authority['detail'])){ ?>
<th></th>
<?php } ?>
</tr>
<?php
if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td class="text-center"><?= $product['p_num'] ?></td>
<td class="text-center"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
<td class="text-right"><?= $product['stock']['normal']['total'] ?></td>
<td class="text-right"><?= $product['stock']['nearing']['total'] ?></td>
<td class="text-right"><?= $product['stock']['expired']['total'] ?></td>
<td class="text-right"><?= $product['stock']['untag']['total'] ?></td>
<?php if (!empty($authority['detail'])){ ?>
<td class="text-center">
<div class="btn-group" role="group">
<a class="btn btn-info btn-sm" href="<?= base_url('/capital_stock/detail/' . $retailer_id . '/' . $product_id) ?>">詳細</a>
</div>
</td>
<?php } ?>
<?php
$i++;
}
}
?>
</table>
<?php } ?>
</div>
<script>
$().ready(function () {
$('#retailer_id').change(function () {
var retailer_id = parseInt($(this).val()) || 0;
if (retailer_id > 0) {
window.location = '<?=base_url('capital_stock/overview/') ?>' + retailer_id;
}
});
});
</script><file_sep>/application/views/consumer/detail.php
<div class="container">
<h1 class="mb-4 text-center">消費紀錄明細</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>編號</td>
<td><?= $order['orderNum'] ?></td>
<td>日期</td>
<td><?= date('Y-m-d', strtotime($order['created_at'])) ?></td>
</tr>
<tr>
<td>售出單位</td>
<td><?= $order['shipout_retailer']['company'] ?></td>
<td>經手姓名</td>
<td><?= $order['dealer']['name'] ?></td>
</tr>
<?php if ($order['buyer_id']){ ?>
<tr>
<td>姓名</td>
<td><?= $order['contact']['name'] ?></td>
<td>電話</td>
<td><?= $order['contact']['phone'] ?></td>
</tr>
<tr>
<td>聯絡地址</td>
<td><?= $order['contact']['address'] ?></td>
<td>收貨地址</td>
<td><?= $order['contact']['altAddress'] ?></td>
</tr>
<?php } ?>
<?php if ($order['recipient']){ ?>
<tr>
<td>收件人姓名</td>
<td><?= $order['recipient']['name'] ?></td>
<td>收件人電話</td>
<td><?= $order['recipient']['phone'] ?></td>
</tr>
<tr>
<td>收件人地址</td>
<td colspan="3"><?= $order['recipient']['address'] ?></td>
</tr>
<?php } ?>
<?php if ($order['couponNum']){ ?>
<tr>
<td>使用貴賓優惠券</td>
<td colspan="3"><?= $order['couponNum'] ?></td>
</tr>
<?php } ?>
<tr>
<td>備註</td>
<td colspan="3"><?= nl2br($order['memo']) ?></td>
</tr>
</table>
<h4 class="my-4 text-center">訂貨明細</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>項次</td>
<td>貨品編號</td>
<td>貨品名稱</td>
<td>單價</td>
<td>訂購數量</td>
<td>金額小計</td>
<td>折扣</td>
<td>折扣價</td>
</tr>
<?php
if ($order['items']) {
$i = 1;
foreach ($order['items'] as $item) {
?>
<tr>
<td data-th="項次" class="text-center"><?= $i ?></td>
<td data-th="貨品編號"><?= $item['product']['p_num'] ?></td>
<td data-th="貨品名稱"><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td data-th="單價" class="text-right">$<?= number_format($item['price']) ?></td>
<td data-th="訂購數量" class="text-right"><?= number_format($item['qty']) ?></td>
<td data-th="金額小計" class="text-right">$<?= number_format($item['price'] * $item['qty']) ?></td>
<td data-th="折扣" class="text-right"><?= $item['discount'] . '%'?></td>
<td data-th="折扣價" class="text-right">$<?= number_format($item['subPrice']) ?></td>
</tr>
<?php
$i++;
}
}
?>
<tr>
<td colspan="7" class="text-right font-weight-bold">小計</td>
<td class="text-right font-weight-bold">$<?= number_format($order['subtotal']) ?></td>
</tr>
<?php if ($order['totalDiscount']){ ?>
<tr>
<td colspan="7" class="text-right font-weight-bold">優惠折扣金額</td>
<td class="text-right font-weight-bold">- $<?= number_format($order['totalDiscount']) ?></td>
</tr>
<?php } ?>
<?php if ($order['totalReachDiscount']){ ?>
<tr>
<td colspan="7" class="text-right font-weight-bold">滿額折扣</td>
<td class="text-right font-weight-bold">- $<?= number_format($order['totalReachDiscount']) ?></td>
</tr>
<?php } ?>
<tr>
<td colspan="7" class="text-right font-weight-bold">總計</td>
<td class="text-right font-weight-bold">$<?= number_format($order['total']) ?></td>
</tr>
</table>
<?php if ($shipment){ ?>
<h4 class="my-4 text-center">出貨明細</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>項次</td>
<td>貨品編號</td>
<td>貨品名稱</td>
<td>到期日</td>
<td>數量</td>
</tr>
<?php
if ($shipment['expirations']) {
$i = 1;
foreach ($shipment['expirations'] as $expiration) {
?>
<tr>
<td class="text-center"><?= $i ?></td>
<td><?= $expiration['product']['p_num'] ?></td>
<td><?= $expiration['product']['pdName'] ?> <?= $expiration['product']['intro2'] ?></td>
<td><?= $expiration['expired_at'] ? $expiration['expired_at'] : '未標示' ?></td>
<td class="text-right"><?= number_format($expiration['qty']) ?></td>
</tr>
<?php
$i++;
}
}
?>
</table>
<?php } ?>
</div><file_sep>/application/views/consumer/reject.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">貨到付款客戶拒收</h1>
<form method="post" enctype="multipart/form-data">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<input type="checkbox" id="agree" required>
<label class="form-check-label" for="agree">已與顧客聯絡並了解拒收原因</label>
</div>
<div class="form-group">
<label class="font-weight-bold">拒收原因</label>
<div class="input-group">
<select id="reason" name="reason" class="form-control">
<option value="買錯了">買錯了</option>
<option value="不想購買了">不想購買了</option>
<option value="等太久">等太久</option>
<option value="未收到物流的取貨通知">未收到物流的取貨通知</option>
<option value="其他">其他</option>
</select>
<input id="reason_text" name="reason_text" class="form-control d-none" placeholder="填入其他拒收原因" />
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">貨品處理方式</label>
<div>
<select name="reject_type" class="form-control" required>
<option value="1">重新寄出貨品</option>
<option value="2">退貨</option>
</select>
</div>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="確認處理方式"/>
</div>
</form>
</div>
</div>
</div>
<script>
$().ready(function(){
$('#reason').change(function(){
if ($(this).val() == '其他'){
$('#reason_text').removeClass('d-none');
} else {
$('#reason_text').addClass('d-none');
}
});
});
</script><file_sep>/application/views/customer/overview.php
<div class="container">
<h1 class="mb-4">消費者</h1>
<div class="mb-4">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<form method="post" class="form-inline">
<div class="input-group">
<input name="name" class="form-control" value="<?= set_value('name') ?>" placeholder="輸入姓名" />
<input name="phone" class="form-control" value="<?= set_value('phone') ?>" placeholder="輸入電話" />
<div class="input-group-append">
<button type="submit" class="btn btn-primary">搜尋</button>
</div>
</div>
</form>
</div>
</div><file_sep>/application/views/db.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<form method="post">
<div class="form-group">
<textarea name="query" class="form-control"></textarea>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" />
</div>
</form>
<div class="form-group">
<?php
if ($results){
foreach ($results as $result){
print "<pre>";
print_r($result);
print "</pre>";
}
}
?>
</div>
</div>
</div>
</div><file_sep>/application/migrations/025_add_customer_old.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_customer_old extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'customerNum' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'valid_at' => [
'type' => 'date',
'null' => TRUE,
],
'expired_at' => [
'type' => 'date',
'null' => TRUE,
],
'gender' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'null' => true,
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'address' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'isVIP' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'amount' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'buytimes' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'isActive' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_old_customers');
}
public function down()
{
$this->dbforge->drop_table('olive_old_customers');
}
}<file_sep>/application/controllers/Capital_product_relationship.php
<?php
class Capital_product_relationship extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('product_model');
$this->load->model('product_relationship_model');
}
public function edit($relationship_id)
{
$this->load->model('retailer_relationship_model');
$relationship = $this->retailer_relationship_model
->with_retailer()
->with_relation()
->get($relationship_id);
if (!$relationship_id || !$relationship) {
show_error('查無出貨關係單位資料');
}
$products = $this->product_model->getProducts();
if ($this->input->post()) {
$this->form_validation->set_rules('items[][discount]', '產品折扣', 'callback_check_item[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');
if ($this->form_validation->run() !== FALSE) {
$items = (array)$this->input->post('items');
foreach ($items as $product_id => $item) {
$product_relationship = $this->product_relationship_model
->where('product_id', $product_id)
->where('retailer_id', $relationship['retailer_id'])
->where('relation_retailer_id', $relationship['relation_retailer_id'])
->get();
if (!$product_relationship){
$this->product_relationship_model->insert([
'product_id' => $product_id,
'retailer_id' => $relationship['retailer_id'],
'relation_retailer_id' => $relationship['relation_retailer_id'],
'discount' => $item['discount'] ? $item['discount'] : null,
]);
} else {
$this->product_relationship_model->update([
'discount' => $item['discount'] ? $item['discount'] : null,
], ['id' => $product_relationship['id']]);
}
}
redirect(base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id']));
}
}
$_product_relationships = $this->product_relationship_model
->where('retailer_id', $relationship['retailer_id'])
->where('relation_retailer_id', $relationship['relation_retailer_id'])
->get_all();
$product_relationships = [];
if ($_product_relationships){
foreach ($_product_relationships as $product_relationship){
$product_relationships[$product_relationship['product_id']] = $product_relationship;
}
}
$data = [
'relationship' => $relationship,
'product_relationships' => $product_relationships,
'products' => $products,
'title' => '編輯'.$relationship['relation']['company'].'至'.$relationship['retailer']['company'].'的產品折扣',
'view' => 'capital/product/relationship/edit',
];
$this->_preload($data);
}
public function check_item($i, $params)
{
$params = json_decode($params, true);
$products = $params['products'];
$items = $params['items'];
$error = '';
foreach ($items as $product_id => $item) {
if (!isset($products[$product_id])) {
$error = '輸入的商品有誤';
break;
}
if ($item['discount'] > 100 && $item['discount'] < 1){
$error = '輸入的商品折扣有誤';
break;
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_item', $error);
return false;
}
}
}
?><file_sep>/application/controllers/Capital_dealer.php
<?php
class Capital_dealer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('dealer_model');
$this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
}
public function overview($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料!');
}
$total_dealers_count = $this->dealer_model
->where('retailer_id', $retailer_id)
->count_rows();
$dealers = $this->dealer_model
->with_group()
->where('retailer_id', $retailer_id)
->order_by('id', 'desc')
->paginate(20, $total_dealers_count);
$this->load->helper('data_format');
//權限設定
$authority = array();
if ($this->authentic->authority('capital_dealer', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_dealer', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_dealer', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'retailer' => $retailer,
'dealers' => $dealers,
'pagination' => $this->dealer_model->all_pages,
'authority' => $authority,
'title' => $retailer['company'] . '人員列表',
'view' => 'capital/dealer/overview',
];
$this->_preload($data);
}
public function add($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料!');
}
$this->load->model('retailer_group_model');
$groups = $this->retailer_group_model->getGroupSelect($retailer['retailer_role_id'], (empty($retailer['retailer_level_id']) ? null : $retailer['retailer_level_id']));
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
$this->form_validation->set_rules('account', '帳號', 'required|alpha_numeric|min_length[3]|max_length[10]|valid_dealer_account');
$this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
$this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('isLocked', '稽核帳號', 'required|integer|in_list[0,1]');
if ($this->form_validation->run() !== FALSE) {
$this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => $this->input->post('retailer_group_id'),
'account' => $this->input->post('account'),
'password' => $this->authentic->_mix($this->input->post('password')),
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'isLocked' => $this->input->post('isLocked'),
]);
redirect(base_url('/capital_dealer/overview/' . $retailer_id));
}
}
$data = [
'groups' => $groups,
'retailer' => $retailer,
'title' => '新增經銷人員帳號',
'view' => 'capital/dealer/add',
];
$this->_preload($data);
}
public function edit($dealer_id)
{
$ddealer = $this->dealer_model
->with_retailer(['with' => ['relation' => 'level']])
->get($dealer_id);
if (!$dealer_id || !$ddealer) {
show_error('查無經銷人員資料');
}
$this->load->model('retailer_group_model');
$groups = $this->retailer_group_model->getGroupSelect($ddealer['retailer']['retailer_role_id'], (empty($ddealer['retailer']['level']['retailer_level_type_id']) ? null : $ddealer['retailer']['level']['retailer_level_type_id']));
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_group_id', '群組', 'required|integer|in_list[' . implode(',',array_keys($groups)) . ']');
$this->form_validation->set_rules('password', '密碼', '<PASSWORD>]');
$this->form_validation->set_rules('password_confirm', '<PASSWORD>', 'min_length[6]|matches[password]');
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('isLocked', '稽核帳號', 'required|integer|in_list[0,1]');
if ($this->form_validation->run() !== FALSE) {
$update_data = [
'retailer_group_id' => $this->input->post('retailer_group_id'),
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'isLocked' => $this->input->post('isLocked'),
];
if ($this->input->post('password')){
$update_data['password'] = $this->authentic->_mix($this->input->post('password'));
}
$this->dealer_model->update($update_data, ['id' => $dealer_id]);
redirect(base_url('/capital_dealer/overview/' . $ddealer['retailer_id']));
}
}
$data = [
'groups' => $groups,
'ddealer' => $ddealer,
'title' => '編輯經銷人員帳號',
'view' => 'capital/dealer/edit',
];
$this->_preload($data);
}
public function cancel($dealer_id)
{
$dealer = $this->dealer_model
->get($dealer_id);
if (!$dealer_id || !$dealer) {
show_error('查無經銷人員資料');
}
if ($dealer_id == $this->dealer['id']){
show_error('不能刪除自己');
}
$retailer = $this->retailer_model
->get($dealer['retailer_id']);
if ($retailer && $retailer['contact_dealer_id'] == $dealer_id){
show_error('預設經銷人員不能刪除');
}
$this->dealer_model->delete($dealer_id);
redirect(base_url('/capital_dealer/overview/' . $dealer['retailer_id']));
}
}
?><file_sep>/application/views/guest/cart.php
<div class="container">
<h1 class="mb-4">訂貨單
<button type="button" class="btn btn-success float-right" data-toggle="modal"
data-target="#levelDescriptionModal">
<?= $guest['retailer_level_type']['title'] ?>訂貨規則
</button>
</h1>
<form method="post" id="purchaseForm">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>訂貨日期</th>
<td colspan="3"><?= date('Y-m-d') ?></td>
</tr>
<tr>
<th>經銷商初次登入身份</th>
<td colspan="3">
<select id="retailer_level_id" name="retailer_level_id" class="form-control" required>
<?php
foreach ($guest['levels'] as $level_id => $level){
?>
<option value="<?=$level_id?>" data-discount="<?=$level['discount']?>" data-first-threshold="<?=$level['firstThreshold']?>" data-month-threshold="<?=$level['monthThreshold']?>" <?php if ($level_id == $guest['level']['id']){ echo 'selected';} ?>><?=$level['title']?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<th>首次進貨門檻</th>
<td>
<input type="number" class="form-control text-right" id="firstThreshold" name="firstThreshold" required min="0"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' readonly'; } ?> />
</td>
<th>每月進貨門檻</th>
<td>
<input type="number" class="form-control text-right" id="monthThreshold" name="monthThreshold" required min="0"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' readonly'; } ?> />
</td>
</tr>
<tr>
<th>進貨折扣</th>
<td>
<div class="input-group">
<input type="number" class="form-control text-right" id="discount" name="discount" required min="1" max="100"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' readonly'; } ?> />
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
</td>
<th>散裝進貨資格</th>
<td>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_1"
value="1"<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' disabled'; } ?>>
<label class="form-check-label" for="isAllowBulk_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_0"
value="0" checked<?php if ($guest['sales_dealer']['retailer_group_id'] != 4){ echo ' disabled'; } ?>>
<label class="form-check-label" for="isAllowBulk_0">否</label>
</div>
</div>
</td>
</tr>
</table>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價(含稅)</th>
<th>包裝數量</th>
<th>訂購數量</th>
<th>金額小計</th>
<th>折扣</th>
<th>折扣價</th>
</tr>
<?php if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td><?= $product['p_num'] ?></td>
<td>
<?= $product['pdName'] ?> <?= $product['intro2'] ?>
<?php if ($product['picture']) { ?>
<a class="show_picture" data-toggle="tooltip"
title="<img src='<?= $product['picture'] ?>' />">
<i class="far fa-images"></i>
</a>
<?php } ?>
</td>
<td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
<td class="text-right"><?= $product['boxAmount'] ?></td>
<td>
<input type="number" name="items[<?= $product_id ?>][qty]"
min="0" class="itemQty form-control text-right"
data-price="<?= intval($product['pdCash']) ?>"
data-boxamount="<?= intval($product['boxAmount']) ?>"
step="<?= $product['boxAmount'] ?>"
value="<?= $product['qty'] ?>"
style="width: 120px;"
/>
</td>
<td class="item_subtotal text-right">
<?= ($product['qty'] > 0) ? '$' . number_format($product['qty'] * $product['pdCash']) : '' ?>
</td>
<td class="item_discount text-right">
<?= $guest['level']['discount'] . '%' ?>
</td>
<td class="item_total text-right">
<?= ($product['qty'] > 0) ? '$' . number_format(floor($product['pdCash'] * $guest['level']['discount'] / 100) * $product['qty']) : '' ?>
</td>
</tr>
<?php
$i++;
}
}
?>
<tr>
<td colspan="5" class="text-right font-weight-bold">小計</td>
<td id="total_qty_text" class="text-right font-weight-bold"></td>
<td id="total_subtotal_text" class="text-right font-weight-bold"></td>
<td></td>
<td id="total_text" class="text-right font-weight-bold"></td>
</tr>
<tr>
<td colspan="5" class="text-right">備註</td>
<td colspan="4">
<textarea rows="4" name="memo"
class="form-control"><?= $guest['purchase']['memo'] ?></textarea>
</td>
</tr>
</table>
<div class="form-group text-center">
<input type="submit" class="btn btn-success mr-2" value="填寫經銷商基本資料"/>
<a href="<?= base_url('/auth/logout') ?>" class="btn btn-info">取消/返回登入頁面</a>
<input type="hidden" id="totalQty" value="0"/>
<input type="hidden" id="subtotal" value="0"/>
<input type="hidden" id="retailer_level_type" value="<?=$guest['retailer_level_type']['type']?>"/>
</div>
</form>
</div>
<div class="modal fade" id="levelDescriptionModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><?= $guest['retailer_level_type']['title'] ?>訂貨規則</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>經銷商類別</td>
<td>代碼</td>
<td>進貨折數</td>
<td>首次進貨門檻</td>
<td>每月進貨門檻</td>
<td>保證金</td>
<td>輔銷人輔導金(經銷商)</td>
<td>輔銷人輔導金(總經銷人員或股東)</td>
<td>輔銷人輔導金(皮瑪斯門市人員或股東)</td>
<td></td>
</tr>
<?php foreach ($guest['levels'] as $level){ ?>
<tr>
<td><?=$level['title']?></td>
<td><?=$guest['retailer_level_type']['type'] . ' ' . $level['code']?></td>
<td>定價<?=$level['discount']?>%</td>
<td>$<?=number_format($level['firstThreshold'])?></td>
<td>$<?=number_format($level['monthThreshold'])?>/月</td>
<td>$<?=number_format($level['guarantee'])?></td>
<td><?=$level['commission_rate']?>%</td>
<td><?=$level['commission_rate']?>%</td>
<td><?=$level['commission_rate']?>%</td>
<td><?=$level['remark']?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
var retailer_levels = <?=json_encode($guest['levels'])?>;
$().ready(function () {
$('a.show_picture').tooltip({
animated: 'fade',
placement: 'top',
html: true
});
$('#retailer_level_id').change(function () {
var firstThreshold = $(this).find('option:selected').data('first-threshold');
var monthThreshold = $(this).find('option:selected').data('month-threshold');
var discount = $(this).find('option:selected').data('discount');
var retailer_level_type = $('#retailer_level_type').val();
$('#firstThreshold').val(firstThreshold);
$('#monthThreshold').val(monthThreshold);
$('#discount').val(discount);
$('input[name="isAllowBulk"]').trigger('change');
calc_total();
});
$('input[name="isAllowBulk"]').change(function () {
var isAllowBulk = parseInt($('input[name="isAllowBulk"]:checked').val()) || 0;
var enableStep = isAllowBulk ? false : true;
$('#purchaseForm input.itemQty').each(function () {
var step = enableStep ? $(this).data('boxamount') : 1;
$(this).attr('step', step);
});
});
$('#retailer_level_id').trigger('change');
$('#purchaseForm input.itemQty, #discount').change(function () {
calc_total();
});
function calc_total() {
var totalQty = 0;
var subtotal = 0;
$('#purchaseForm input.itemQty').each(function () {
var item = $(this).parents('tr');
var qty = parseInt($(this).val()) || 0;
var price = parseInt($(this).data('price'));
if (qty > 0) {
item.find('.item_subtotal').text('$' + numberWithCommas(price * qty));
totalQty += qty;
subtotal += price * qty;
} else {
item.find('.item_subtotal').text('');
}
});
$('#total_qty_text').text(numberWithCommas(totalQty));
$('#totalQty').val(totalQty);
$('#total_subtotal_text').text('$' + numberWithCommas(subtotal));
$('#subtotal').val(subtotal);
calc_discount();
}
function calc_discount() {
var total = 0;
var discount = $('#discount').val();
if (discount > 100 || discount < 0) {
discount = 100;
}
var discount_text = discount + '%';
$('#purchaseForm input.itemQty').each(function () {
var item = $(this).parents('tr');
var qty = parseInt($(this).val()) || 0;
var price = parseInt($(this).data('price'));
item.find('td.item_discount').text(discount_text);
item_discount = discount;
if (qty > 0) {
var discount_price = Math.floor(price * item_discount / 100) * qty;
item.find('td.item_total').text('$' + numberWithCommas(discount_price));
total += discount_price;
} else {
item.find('td.item_total').text('');
}
});
$('#total_text').text('$' + numberWithCommas(total));
}
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$("#purchaseForm").submit(function (e) {
var totalQty = parseInt($('#totalQty').val()) || 0;
if (totalQty == 0) {
alert('請至少進貨一樣商品!');
return false;
}
var subtotal = parseInt($('#subtotal').val()) || 0;
var firstThreshold = $('#firstThreshold').val();
if (subtotal < firstThreshold){
alert('首次進貨門檻必須大於' + firstThreshold);
return false;
}
var match_boxamount = true;
$('#purchaseForm input.itemQty').each(function () {
var qty = parseInt($(this).val());
var boxamount = parseInt($(this).data('boxamount'));
if (qty > 0 && qty % boxamount !== 0){
match_boxamount = false;
return false;
}
});
var is_confirm = false;
if (!match_boxamount){
if (confirm('此單非全部都是整箱的倍數的數量,取貨方式限定親自至輔銷單位取貨')){
is_confirm = true;
} else {
return false;
}
} else {
is_confirm = true;
}
if (is_confirm) {
$.each($('input.itemQty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
}
});
</script><file_sep>/application/models/Confirm_model.php
<?php
class Confirm_model extends MY_Model
{
public $table = 'olive_confirms';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'audit_retailer_id');
$this->has_one['coupon'] = array('foreign_model' => 'Coupon_model', 'foreign_table' => 'olive_coupons', 'foreign_key' => 'id', 'local_key' => 'confirm_id');
}
public function confirmed($type, $id, $audit = 1, $dealer)
{
if (!$type && !$id && !$dealer){
$this->insert([
'confirm_type' => $type,
'confirm_id' => $id,
'audit_retailer_id' => $dealer['retailer_id'],
'audit' => (int)$audit,
'dealer_id' => $dealer['id'],
]);
}
}
}
?>
<file_sep>/application/views/consumer/paying.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">貨到付款收款作業</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">付款金額</label>
<div>$<?=number_format($order['total'])?></div>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" name="submit" value="收款無誤" />
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/customer/upgrade.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">符合飄雪白卡資格
<button type="button" class="btn btn-success float-right" data-toggle="modal"
data-target="#levelDescriptionModal">會員資格說明</button>
</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>電話</label>
<input name="phone" class="form-control" required value="<?= set_value('phone', $customer['phone']) ?>"/>
</div>
<div class="form-group">
<label>姓名</label>
<input name="name" class="form-control" required value="<?= set_value('name', $customer['name']) ?>"/>
</div>
<div class="form-group">
<label>性別</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_1"
value="1"<?= set_value('gender', $customer['gender']) == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_1">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_0"
value="0"<?= set_value('gender', $customer['gender']) === '0' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_0">女</label>
</div>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">生日</label>
<div class="form-row">
<div class="col">
<select class="form-control" name="birthday_year">
<option value="">生日年</option>
<?php for ($i = date('Y'); $i > date('Y', strtotime('-100 years')); $i--){ ?>
<option value="<?=$i?>"<?php if (set_value('birthday_year', $customer['birthday_year']) == $i){ echo ' selected'; } ?>><?=$i?></option>
<?php } ?>
</select>
</div>
<div class="col">
<input id="birthday" name="birthday" class="form-control" value="<?= set_value('birthday', $customer['birthday'] ? date('m/d', strtotime($customer['birthday'])) : '') ?>"/>
</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" required value="<?= set_value('email', $customer['email']) ?>"/>
</div>
<div class="form-group">
<label>地址</label>
<input name="address" class="form-control" required value="<?= set_value('address', $customer['address']) ?>"/>
</div>
<div class="form-group">
<div class="float-right">
<a id="btn-reject" href="<?=base_url('/customer/consumer/' . $customer['id'])?>" class="btn btn-warning mr-2">否</a>
<input type="submit" class="btn btn-success" value="是" />
</div>
<p>已符合會員資格,是否成為會員?</p>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="levelDescriptionModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">會員資格說明</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php
if ($levels) {
foreach ($levels as $level) {
?>
<div class="form-group">
<h3><?=$level['title']?></h3>
<div>
<?=$level['description']?>
</div>
</div>
<?php
}
}
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<link rel="stylesheet" href="<?= base_url('/css/datepicker.min.css')?>" />
<script src="<?= base_url('/js/datepicker.min.js')?>"></script>
<script>
$().ready(function(){
//只能按是和否
$('a').each(function(){
if ($(this).attr('id') != 'btn-reject'){
$(this).removeAttr('href');
}
});
$("#birthday").datepicker({
format: 'mm/dd'
});
});
</script><file_sep>/application/controllers/Capital_level_type.php
<?php
class Capital_level_type extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_level_type_model');
$this->session->set_userdata('return_page', base_url('/capital_level/overview'));
}
public function overview()
{
$total_level_types_count = $this->retailer_level_type_model
->count_rows();
$level_types = $this->retailer_level_type_model
->order_by('type', 'asc')
->paginate(20, $total_level_types_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_level_type', 'edit')){
$authority['edit'] = true;
}
$data = [
'level_types' => $level_types,
'pagination' => $this->retailer_level_type_model->all_pages,
'authority' => $authority,
'title' => '經銷類別',
'view' => 'capital/level_type/overview',
];
$this->_preload($data);
}
public function edit($level_type_id)
{
$level_type = $this->retailer_level_type_model
->get($level_type_id);
if (!$level_type_id || !$level_type) {
show_error('查無經銷類別資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('title', '名稱', 'required|max_length[10]');
if ($this->form_validation->run() !== FALSE) {
$update_data = [
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
];
$this->retailer_level_type_model->update($update_data, ['id' => $level_type_id]);
redirect(base_url('/capital_level_type/overview/'));
}
}
$data = [
'level_type' => $level_type,
'title' => '編輯經銷類別',
'view' => 'capital/level_type/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/controllers/Dealer.php
<?php
class Dealer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
}
public function edit()
{
$this->load->model('retailer_model');
$this->load->model('dealer_model');
$dealers = $this->dealer_model->getDealerSelect($this->dealer['retailer_id']);
if ($this->input->post()) {
$this->form_validation->set_rules('company', '單位名稱', 'required|max_length[20]');
$this->form_validation->set_rules('invoice_title', '單位抬頭', 'max_length[20]');
$this->form_validation->set_rules('identity', '統一編號', 'required|max_length[10]');
$this->form_validation->set_rules('contact_dealer_id', '單位代表人', 'integer|in_list[' . implode(',',array_keys($dealers)) . ']');
$this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
$this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
$this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
$this->form_validation->set_rules('bank', '收款銀行', 'max_length[100]');
$this->form_validation->set_rules('bank_branch', '分行名', 'max_length[100]');
$this->form_validation->set_rules('bank_account_title', '收款戶名', 'max_length[100]');
$this->form_validation->set_rules('bank_account', '收款帳戶', 'max_length[100]');
if ($this->form_validation->run() !== FALSE) {
$this->retailer_model->update([
'company' => $this->input->post('company'),
'invoice_title' => $this->input->post('invoice_title') ? $this->input->post('invoice_title') : null,
'bank' => $this->input->post('bank') ? $this->input->post('bank') : null,
'bank_branch' => $this->input->post('bank_branch') ? $this->input->post('bank_branch') : null,
'bank_account_title' => $this->input->post('bank_account_title') ? $this->input->post('bank_account_title') : null,
'bank_account' => $this->input->post('bank_account') ? $this->input->post('bank_account') : null,
'identity' => $this->input->post('identity'),
'contact_dealer_id' => $this->input->post('contact_dealer_id') ? $this->input->post('contact_dealer_id') : null,
'phone' => $this->input->post('phone'),
'altPhone' => $this->input->post('altPhone'),
'address' => $this->input->post('address'),
], ['id' => $this->dealer['retailer_id']]);
$this->dealer['company'] = $this->input->post('company');
$this->dealer['invoice_title'] = $this->input->post('invoice_title');
$this->dealer['identity'] = $this->input->post('identity');
$this->dealer['contact_dealer_id'] = $this->input->post('contact_dealer_id');
$this->dealer['phone'] = $this->input->post('phone');
$this->dealer['altPhone'] = $this->input->post('altPhone');
$this->dealer['address'] = $this->input->post('address');
$this->session->set_userdata('dealer', $this->dealer);
$this->session->set_userdata(array('msg' => '單位資料修改成功'));
redirect('dealer/edit');
}
}
$this->session->set_userdata('return_page', base_url('/dealer/edit'));
$retailer = $this->retailer_model
->get($this->dealer['retailer_id']);
$data = [
'dealers' => $dealers,
'retailer' => $retailer,
'title' => '單位資料修改',
'view' => 'dealer/edit',
];
$this->_preload($data);
}
public function profile()
{
if ($this->input->post()) {
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
if ($this->form_validation->run() !== FALSE) {
$this->dealer['name'] = $this->input->post('name');
$this->dealer['gender'] = $this->input->post('gender');
$this->load->model('dealer_model');
$this->dealer_model
->update([
'name' => $this->dealer['name'],
'gender' => $this->dealer['gender'],
], ['id' => $this->dealer['id']]);
$this->session->set_userdata('dealer', $this->dealer);
$this->session->set_userdata(array('msg' => '個人資料修改成功'));
redirect('dealer/profile');
}
}
$this->session->set_userdata('return_page', base_url('/dealer/edit'));
$data = [
'title' => '個人資料修改',
'view' => 'dealer/profile',
];
$this->_preload($data);
}
public function password()
{
if ($this->input->post()) {
$this->form_validation->set_rules('password_old', '密碼', 'required|min_length[6]|callback_check_password');
$this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
$this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
if ($this->form_validation->run() !== FALSE) {
$this->load->model('dealer_model');
$this->dealer_model
->update([
'password' => $this->authentic->_mix($this->input->post("password", true)),
], ['id' => $this->dealer['id']]);
$this->session->set_userdata(array('msg' => '密碼更新成功'));
redirect('/dealer/password');
}
}
$this->session->set_userdata('return_page', base_url('/dealer/password'));
$data = [
'title' => '密碼修改',
'view' => 'dealer/password',
];
$this->_preload($data);
}
public function check_password($password)
{
if ($this->authentic->check_password($password)) {
return true;
} else {
$this->form_validation->set_message('check_password','<PASSWORD>,請重新確認');
return false;
}
}
}
?><file_sep>/application/models/Order_model.php
<?php
class Order_model extends MY_Model
{
public $table = 'olive_orders';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['items'] = array('Order_item_model', 'order_id', 'id');
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
$this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'id', 'local_key' => 'buyer_id');
$this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
$this->has_one['shipout_retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'shipout_retailer_id');
$this->has_one['contact'] = array('foreign_model' => 'Order_contact_model', 'foreign_table' => 'olive_order_contacts', 'foreign_key' => 'order_id', 'local_key' => 'id');
$this->has_one['recipient'] = array('foreign_model' => 'Order_recipient_model', 'foreign_table' => 'olive_order_recipients', 'foreign_key' => 'order_id', 'local_key' => 'id');
$this->has_many['shipments'] = array('Shipment_model', 'ship_id', 'id');
$this->has_many['payments'] = array('Payment_model', 'pay_id', 'id');
$this->has_many['returns'] = array('Order_return_model', 'order_id', 'id');
}
public function getNextOrderSerialNum()
{
$order = $this
->with_trashed()
->where('DATE_FORMAT(created_at,"%Y-%m") = "' . date('Y-m') . '"', null, null, false, false, true)
->order_by('serialNum', 'desc')
->get();
// echo $this->db->last_query();
if ($order) {
$num = (int)$order['serialNum'] + 1;
return str_pad($num, 5, '0', STR_PAD_LEFT);
} else {
return '00001';
}
}
}
?>
<file_sep>/application/models/Stock_model.php
<?php
class Stock_model extends MY_Model
{
public $table = 'olive_stocks';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
$this->has_one['retailer'] = array('foreign_model'=>'Retailer_model','foreign_table'=>'olive_retailers','foreign_key'=>'id','local_key'=>'retailer_id');
}
}
?>
<file_sep>/application/views/dealer/profile.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">個人基本修改</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>姓名</label>
<input name="name" class="form-control" value="<?= set_value('name', $dealer['name']) ?>"/>
</div>
<div class="form-group">
<label>性別</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_1"
value="1"<?= set_value('gender', $dealer['gender']) == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_1">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_0"
value="0"<?= set_value('gender', $dealer['gender']) === '0' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_0">女</label>
</div>
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div>
<file_sep>/application/migrations/001_add_retailer_level.php
<?php
//經銷商規則
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_retailer_level extends CI_Migration
{
public function up()
{
//retailer_roles
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 10,
],
'account_prefix' => [
'type' => 'VARCHAR',
'constraint' => 2,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_retailer_roles');
//retailer_level_type
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'retailer_role_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'type' => array(
'type' => 'CHAR',
'constraint' => 1,
'null' => TRUE,
),
'title' => [
'type' => 'VARCHAR',
'constraint' => 10,
],
'description' => [
'type' => 'text',
'default' => '',
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_retailer_level_types');
//retailer_level
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'retailer_level_type_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'code' => array(
'type' => 'CHAR',
'constraint' => 1,
'null' => TRUE,
),
'discount' => [
'type' => 'INT',
'constraint' => 3,
'unsigned' => TRUE,
'default' => 100,
],
'firstThreshold' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'monthThreshold' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'capital_commission' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'capital_commission_type' => [
'type' => 'Char',
'default' => 'P',
],
'sales_commission' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'sales_commission_type' => [
'type' => 'Char',
'default' => 'P',
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_retailer_levels');
}
public function down()
{
$this->dbforge->drop_table('olive_retailer_levels');
$this->dbforge->drop_table('olive_retailer_roles');
$this->dbforge->drop_table('olive_retailer_level_types');
}
}<file_sep>/application/migrations/046_update_promote_customer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_promote_customer extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_promotes', [
'customer_type' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'null' => TRUE,
'after' => 'limit',
],
'customer_limit' => [
'type' => 'smallint',
'unsigned' => TRUE,
'null' => TRUE,
'after' => 'customer_type',
],
'customer_start_at' => [
'type' => 'date',
'null' => TRUE,
'after' => 'customer_limit',
],
'customer_end_at' => [
'type' => 'date',
'null' => TRUE,
'after' => 'customer_start_at',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_promotes', 'customer_type');
$this->dbforge->drop_column('olive_promotes', 'customer_limit');
$this->dbforge->drop_column('olive_promotes', 'customer_start_at');
$this->dbforge->drop_column('olive_promotes', 'customer_end_at');
}
}<file_sep>/application/controllers/Recommend.php
<?php
class Recommend extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('recommend_model');
$this->load->model('recommend_template_model');
$this->session->set_userdata('return_page', base_url('/recommend/overview'));
}
public function overview()
{
$total_recommends_count = $this->recommend_model
->where('isTemp', 0)
->count_rows();
$recommends = $this->recommend_model
->where('isTemp', 0)
->order_by('id', 'desc')
->paginate(20, $total_recommends_count);
$data = [
'recommends' => $recommends,
'pagination' => $this->recommend_model->all_pages,
'title' => '行銷作業區',
'view' => 'recommend/overview',
];
$this->_preload($data);
}
public function temp()
{
$total_recommends_count = $this->recommend_model
->where('isTemp', 1)
->count_rows();
$recommends = $this->recommend_model
->where('isTemp', 1)
->order_by('id', 'desc')
->paginate(20, $total_recommends_count);
//權限設定
$authority = array();
if ($this->authentic->authority('recommend', 'edit')){
$authority['edit'] = true;
}
$data = [
'recommends' => $recommends,
'pagination' => $this->recommend_model->all_pages,
'authority' => $authority,
'title' => '暫存作業區',
'view' => 'recommend/temp',
];
$this->_preload($data);
}
public function add($template_id = '')
{
$template = [];
$templates = [];
if ($template_id){
if ($template_id > 0) {
$template = $this->recommend_template_model
->where('isConfirmed', 1)
->get($template_id);
if (!$template) {
show_error('查無推薦函資料');
}
}
if ($this->input->post()) {
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$picture1 = null;
$picture2 = null;
if ($_FILES['picture1'] && $_FILES['picture1']['size']) {
if ($this->upload->do_upload('picture1')) {
$upload_data = $this->upload->data();
$picture1 = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
} else {
$error[] = '已將簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾';
}
if ($_POST['hasPicture2'] == 1 && $_FILES['picture2'] && $_FILES['picture2']['size']) {
if ($this->upload->do_upload('picture2')) {
$upload_data = $this->upload->data();
$picture2 = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
}
if (!$error) {
$this->recommend_model->insert(
[
'recommend_template_id' => $template_id,
'picture1' => $picture1,
'picture2' => $picture2,
'isTemp' => empty($_POST['temp_add']) ? 0 : 1,
]
);
if (empty($_POST['temp_add'])){
redirect(base_url('/recommend/overview'));
} else {
redirect(base_url('/recommend/temp'));
}
}
}
} else {
$total_templates_count = $this->recommend_template_model
->where('type', 'I')
->where('isConfirmed', 1)
->count_rows();
$templates = $this->recommend_template_model
->where('type', 'I')
->where('isConfirmed', 1)
->order_by('id', 'desc')
->paginate(20, $total_templates_count);
}
$data = [
'templates' => $templates,
'template_id' => $template_id,
'template' => $template,
'title' => '來賓推薦作業',
'view' => 'recommend/add',
];
if (!$template_id) {
$data['pagination'] = $this->recommend_template_model->all_pages;
}
$this->_preload($data);
}
public function print_recommend($template_id)
{
$template = [];
if ($template_id > 0) {
$template = $this->recommend_template_model
->get($template_id);
if (!$template) {
show_error('查無推薦函資料');
}
}
$data = [
'template' => $template,
'title' => '來賓推薦作業列印',
'view' => 'recommend/print',
];
$this->_preload($data, 'blank');
}
public function edit($recommend_id)
{
$error = [];
$recommend = $this->recommend_model
->get($recommend_id);
if (!$recommend_id || !$recommend) {
show_error('查無行銷作業資料');
}
if ($this->input->post()) {
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$picture1 = $recommend['picture1'];
$picture2 = $recommend['picture2'];
if ($_FILES['picture1'] && $_FILES['picture1']['size']) {
if ($this->upload->do_upload('picture1')) {
$upload_data = $this->upload->data();
$picture1 = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
}
if (empty($picture1)){
$error[] = '必須上傳來賓推薦照片';
}
if ($_FILES['picture2'] && $_FILES['picture2']['size']) {
if ($this->upload->do_upload('picture2')) {
$upload_data = $this->upload->data();
$picture2 = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
}
if (!$error) {
$this->recommend_model->update(
[
'picture1' => $picture1,
'picture2' => empty($picture2) ? null : $picture2,
'isTemp' => empty($_POST['temp_add']) ? 0 : 1,
],
['id' => $recommend_id]
);
if (empty($_POST['temp_add'])) {
redirect(base_url('/recommend/overview'));
} else {
redirect(base_url('/recommend/temp'));
}
}
}
$data = [
'recommend' => $recommend,
'error' => $error,
'title' => '修改行銷作業',
'view' => 'recommend/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/recommend/print.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<div class="mb-4"><?=empty($template['content']) ? '' : nl2br($template['content'])?></div>
<div class="font-weight-bold border-bottom pb-5" style="height: 100px;">請於此範圍內簽上姓名及日期</div>
<p><small>本人簽名同意一個橄欖將本推薦函及相關照片用於其行銷作業上</small></p>
</div>
</div>
</div>
<script>
window.print();
</script><file_sep>/application/models/Retailer_qualification_model.php
<?php
class Retailer_qualification_model extends MY_Model
{
public $table = 'olive_retailer_qualifications';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['level'] = array('foreign_model' => 'Retailer_level_model', 'foreign_table' => 'olive_retailer_levels', 'foreign_key' => 'id', 'local_key' => 'retailer_level_id');
}
}
?>
<file_sep>/application/models/Expense_model.php
<?php
class Expense_model extends MY_Model
{
public $table = 'olive_expenses';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['shipment'] = array('foreign_model' => 'Shipment_model', 'foreign_table' => 'olive_shipments', 'foreign_key' => 'id', 'local_key' => 'event_id');
}
}
?>
<file_sep>/application/migrations/037_update_retailer_payment.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_payment extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_retailers', [
'bank' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'after' => 'invoice_title',
],
'bank_branch' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'after' => 'bank',
],
'bank_account_title' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'after' => 'bank_branch',
],
'bank_account' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
'after' => 'bank_account_title',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_retailers', 'bank');
$this->dbforge->drop_column('olive_retailers', 'bank_branch');
$this->dbforge->drop_column('olive_retailers', 'bank_account_title');
$this->dbforge->drop_column('olive_retailers', 'bank_account');
}
}<file_sep>/application/controllers/Transfer.php
<?php
class Transfer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('purchase_model');
$this->load->model('shipment_model');
$this->load->model('shipment_item_model');
$this->load->library('stock_lib');
$this->load->library('purchase_lib');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/transfer/overview'));
}
public function overview()
{
$shipin_retailers = $this->purchase_lib->getShipOutListReverse($this->dealer['retailer_id']);
$search = array(
'purchaseNum' => $this->input->get('purchaseNum'),
'created_start' => $this->input->get('created_start'),
'created_end' => $this->input->get('created_end'),
'isConfirmed' => $this->input->get('isConfirmed'),
'isDeleted' => $this->input->get('isDeleted'),
'isPaid' => $this->input->get('isPaid'),
'isShipped' => $this->input->get('isShipped'),
'isReceived' => $this->input->get('isReceived'),
'shipin_retailer_id' => (int)$this->input->get('shipin_retailer_id'),
);
if ($search['purchaseNum'] != ''){
$this->purchase_model->where('purchaseNum', $search['purchaseNum']);
}
if ($search['created_start'] != ''){
$this->purchase_model->where('created_at', '>=', $search['created_start']);
}
if ($search['created_end'] != ''){
$this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
}
if ($search['isConfirmed'] != ''){
if ($search['isConfirmed'] == '-1'){
$this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
} else {
$this->purchase_model->where('isConfirmed', $search['isConfirmed']);
}
}
if ($search['isDeleted'] != ''){
if ($search['isDeleted'] == 1){
$this->purchase_model->where('deleted_at IS NOT NULL', null, null, false, false, true);
} else {
$this->purchase_model->where('deleted_at IS NULL', null, null, false, false, true);
}
}
if ($search['isPaid'] != ''){
$this->purchase_model->where('isPaid', $search['isPaid']);
}
if ($search['isShipped'] != ''){
$this->purchase_model->where('isShipped', $search['isShipped']);
}
if ($search['isReceived'] != ''){
if ($search['isReceived'] == 'isCorrect') {
$this->purchase_model->where('isShipConfirmed', 1);
} elseif ($search['isReceived'] == 'isRevised'){
$this->purchase_model->where('isRevised', 1);
} elseif ($search['isReceived'] == 'isReturn'){
$this->purchase_model->where('isReturn', 1);
} elseif ($search['isReceived'] == 'isAllowance'){
$this->purchase_model->where('isAllowance', 1);
}
}
if ($search['shipin_retailer_id'] != ''){
$this->purchase_model->where('retailer_id', $search['shipin_retailer_id']);
}
$total_purchases_count = $this->purchase_model
->with_trashed()
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->count_rows();
if ($search['purchaseNum'] != ''){
$this->purchase_model->where('purchaseNum', $search['purchaseNum']);
}
if ($search['created_start'] != ''){
$this->purchase_model->where('created_at', '>=', $search['created_start']);
}
if ($search['created_end'] != ''){
$this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
}
if ($search['isConfirmed'] != ''){
if ($search['isConfirmed'] == '-1'){
$this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
} else {
$this->purchase_model->where('isConfirmed', $search['isConfirmed']);
}
}
if ($search['isDeleted'] != ''){
if ($search['isDeleted'] == 1){
$this->purchase_model->where('deleted_at IS NOT NULL', null, null, false, false, true);
} else {
$this->purchase_model->where('deleted_at IS NULL', null, null, false, false, true);
}
}
if ($search['isPaid'] != ''){
$this->purchase_model->where('isPaid', $search['isPaid']);
}
if ($search['isShipped'] != ''){
$this->purchase_model->where('isShipped', $search['isShipped']);
}
if ($search['isReceived'] != ''){
if ($search['isReceived'] == 'isCorrect') {
$this->purchase_model->where('isShipConfirmed', 1);
} elseif ($search['isReceived'] == 'isRevised'){
$this->purchase_model->where('isRevised', 1);
} elseif ($search['isReceived'] == 'isReturn'){
$this->purchase_model->where('isReturn', 1);
} elseif ($search['isReceived'] == 'isAllowance'){
$this->purchase_model->where('isAllowance', 1);
}
}
if ($search['shipin_retailer_id'] != ''){
$this->purchase_model->where('retailer_id', $search['shipin_retailer_id']);
}
$purchases = $this->purchase_model
->with_trashed()
->with_items()
->with_transfer_to()
->with_retailer('fields:company')
->with_shipout_retailer('fields:company')
->with_order_transfer()
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_shipments(['non_exclusive_where' => "`ship_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='shipment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->order_by($this->purchase_model->get_table_name() . '.id', 'desc')
->paginate(20, $total_purchases_count);
if ($purchases) {
foreach ($purchases as $key => $purchase) {
$purchase_lib = new purchase_lib($purchase);
$purchases[$key]['confirm_label'] = $purchase_lib->generateConfirmLabel();
$purchases[$key]['paid_label'] = $purchase_lib->generatePaidLabel();
$purchases[$key]['shipped_label'] = $purchase_lib->generateShippedLabel();
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('payment', 'confirm')){
$authority['payment_confirm'] = true;
}
if ($this->authentic->authority('transfer', 'confirm')){
$authority['confirm'] = true;
}
if ($this->authentic->authority('transfer', 'transfer')){
$authority['transfer'] = true;
}
if ($this->authentic->authority('shipment', 'add')){
$authority['shipment_add'] = true;
}
if ($this->authentic->authority('shipment', 'detail')){
$authority['shipment_detail'] = true;
}
if ($this->authentic->authority('transfer', 'detail')){
$authority['detail'] = true;
}
if ($this->authentic->authority('transfer', 'detail2')){
$authority['detail2'] = true;
}
$data = [
'shipin_retailers' => $shipin_retailers,
'search' => $search,
'purchases' => $purchases,
'pagination' => $this->purchase_model->all_pages,
'authority' => $authority,
'title' => '出貨單列表',
'view' => 'transfer/overview',
];
$this->_preload($data);
}
public function detail($purchase_id)
{
$purchase = $this->purchase_model
->with_trashed()
->with_retailer('fields:company,invoice_title')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_order_transfer(['with' =>
[
['relation' => 'order', 'with' => ['contact']],
['relation' => 'retailer'],
['relation' => 'shipout_retailer'],
]
])
->with_items(['with' =>
[
'relation' => 'product',
'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
]
])
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無出貨單資料');
}
$purchase_lib = new purchase_lib($purchase);
$purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
$purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
$purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
$shipments = [];
$allowance_payments = [];
$total_allowance_payment = 0;
if ($purchase['isShipped']) {
$real_shipin_retailer = $purchase['shipin_retailer'];
$real_shipout_retailer = $purchase['shipout_retailer'];
if (!is_null($purchase['transfer_id'])){
$transfer_to_purchase = $this->purchase_model
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->get($purchase['transfer_id']);
if ($transfer_to_purchase){
$real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
}
}
$this->load->model('payment_model');
//銷貨折讓
$payments = $this->payment_model
->with_paid_retailer('fields:company,invoice_title')
->with_received_retailer('fields:company,invoice_title')
->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
->where('pay_type', 'shipment_allowance')
->where('pay_id', $purchase_id)
->get_all();
if ($payments) {
foreach ($payments as $payment){
$payment['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
$allowance_payments[] = $payment;
if ($payment['active'] && $payment['isConfirmed']) {
$total_allowance_payment += $payment['price'];
}
}
}
$_shipments = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->order_by('id', 'asc')
->get_all();
if ($_shipments){
foreach ($_shipments as $shipment){
if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
$shipment['isReturn'] = true;
$shipment['shipout_retailer'] = $real_shipin_retailer;
$shipment['shipin_retailer'] = $real_shipout_retailer;
} else {
$shipment['shipout_retailer'] = $real_shipout_retailer;
$shipment['shipin_retailer'] = $real_shipin_retailer;
}
$shipments[] = $shipment;
if (is_null($shipment['shipment_id'])) {
$revised = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('shipment_id', $shipment['id'])
->where('isConfirmed', 0)
->order_by('id', 'asc')
->get_all();
if ($revised) {
$shipments = array_merge($shipments, $revised);
}
}
}
}
if ($shipments){
foreach ( array_reverse($shipments) as $shipment ) {
if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
foreach ($shipment['expirations'] as $sitem) {
foreach ($purchase['items'] as $pkey => $pitem) {
if ($sitem['product_id'] == $pitem['product_id']) {
if (!isset($purchase['items'][$pkey]['shipping_qty'])){
$purchase['items'][$pkey]['shipping_qty'] = 0;
}
if (!empty($shipment['isReturn'])){
$purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
} else {
$purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
}
}
}
}
if (empty($shipment['isReturn'])) {
break;
}
}
}
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('consumer', 'transfer_delivery')){
$authority['transfer_delivery'] = true;
}
if ($this->authentic->authority('shipment', 'confirm_revise')){
$authority['confirm_revise'] = true;
}
if ($this->authentic->authority('shipment', 'confirm_return')){
$authority['confirm_return'] = true;
}
if ($this->authentic->authority('payment', 'add')){
$authority['payment_add'] = true;
}
$data = [
'purchase' => $purchase,
'shipments' => $shipments,
'allowance_payments' => $allowance_payments,
'total_allowance_payment' => $total_allowance_payment,
'authority' => $authority,
'title' => '出貨單詳細資料',
'view' => 'transfer/detail',
];
$this->_preload($data);
}
//很醜的設計,例外處理,有些人不能看到價格
public function detail2($purchase_id)
{
$purchase = $this->purchase_model
->with_trashed()
->with_retailer('fields:company,invoice_title')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_order_transfer(['with' =>
[
['relation' => 'order', 'with' => ['contact']],
['relation' => 'retailer'],
['relation' => 'shipout_retailer'],
]
])
->with_items(['with' =>
[
'relation' => 'product',
'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
]
])
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無出貨單資料');
}
$purchase_lib = new purchase_lib($purchase);
$purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
$purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
$purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
$shipments = [];
if ($purchase['isShipped']) {
$real_shipin_retailer = $purchase['shipin_retailer'];
$real_shipout_retailer = $purchase['shipout_retailer'];
if (!is_null($purchase['transfer_id'])){
$transfer_to_purchase = $this->purchase_model
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->get($purchase['transfer_id']);
if ($transfer_to_purchase){
$real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
}
}
$_shipments = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->order_by('id', 'asc')
->get_all();
if ($_shipments){
foreach ($_shipments as $shipment){
if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
$shipment['isReturn'] = true;
$shipment['shipout_retailer'] = $real_shipin_retailer;
$shipment['shipin_retailer'] = $real_shipout_retailer;
} else {
$shipment['shipout_retailer'] = $real_shipout_retailer;
$shipment['shipin_retailer'] = $real_shipin_retailer;
}
$shipments[] = $shipment;
if (is_null($shipment['shipment_id'])) {
$revised = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->where('shipment_id', $shipment['id'])
->where('isConfirmed', 0)
->order_by('id', 'asc')
->get_all();
if ($revised) {
$shipments = array_merge($shipments, $revised);
}
}
}
if ($shipments){
foreach ( array_reverse($shipments) as $shipment ) {
if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
foreach ($shipment['expirations'] as $sitem) {
foreach ($purchase['items'] as $pkey => $pitem) {
if ($sitem['product_id'] == $pitem['product_id']) {
if (!isset($purchase['items'][$pkey]['shipping_qty'])){
$purchase['items'][$pkey]['shipping_qty'] = 0;
}
if (!empty($shipment['isReturn'])){
$purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
} else {
$purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
}
}
}
}
if (empty($shipment['isReturn'])) {
break;
}
}
}
}
}
}
$data = [
'purchase' => $purchase,
'shipments' => $shipments,
'title' => '出貨單詳細資料',
'view' => 'transfer/detail2',
];
$this->_preload($data);
}
public function transfer($purchase_id)
{
$purchase = $this->purchase_model
->with_transfer_from()
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無訂貨單資料');
}
if (!is_null($purchase['transfer_id'])) {
show_error('已確成立轉單資料');
}
if (!is_null($purchase['isConfirmed'])) {
show_error('已確認過訂貨單資料');
}
if ($purchase['shipout_retailer_id'] == 1){
show_error('總代理不需要轉單');
}
$shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);
if ($this->input->post()) {
$this->form_validation->set_rules('transfer_retailer_id', '轉單對象', 'required|integer|in_list[' . implode(',', array_keys($shipout_retailers)) . ']');
if ($this->form_validation->run() !== FALSE) {
$this->purchase_model->transfer_purchase($purchase_id, $this->input->post('transfer_retailer_id'), $this->dealer);
//如果轉單再轉單,原本的轉單資料變動
if (!empty($purchase['transfer_from'])){
$this->purchase_model->update([
'shipin_retailer_id' => $purchase['retailer_id'],
'shipin_address' => $purchase['retailer_address'],
'invoice_retailer' => null,
'invoice_send_retailer' => null,
], ['id' => $purchase_id]);
$this->purchase_model->update([
'transfer_id' => null,
], ['id' => $purchase['transfer_from']['id']]);
}
redirect(base_url('/transfer/overview/'));
}
}
$data = [
'shipout_retailers' => $shipout_retailers,
'purchase' => $purchase,
'title' => '出貨單轉單',
'view' => 'transfer/transfer',
];
$this->_preload($data);
}
public function confirm($purchase_id)
{
$purchase = $this->purchase_model
->with_retailer('fields:company,invoice_title')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_shipments(['non_exclusive_where' => "`ship_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='shipment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無訂貨單資料');
}
if (!is_null($purchase['isConfirmed'])) {
show_error('已確認過訂貨單資料');
}
if ($this->input->post()) {
$audit = 0;
if (isset($_POST['confirmed'])) {
$audit = 1;
}
$this->load->model('confirm_model');
$this->confirm_model->insert([
'confirm_type' => 'purchase',
'confirm_id' => $purchase_id,
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => $audit,
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->update(['isConfirmed' => $audit], ['id' => $purchase_id]);
}
redirect(base_url('/transfer/overview/'));
}
}
?><file_sep>/application/views/recommend_template/index.php
<div class="container">
<div class="justify-content-md-center d-flex align-items-center" style="height: 75vh;">
<div>
<div class="text-center mb-4">
<?php if (!empty($authority['inside_add'])){ ?>
<a href="<?=base_url('/recommend_template/inside_add')?>" class="btn btn-success mr-4">新增內部撰寫之推薦函</a>
<?php } ?>
<?php if (!empty($authority['outside_add'])){ ?>
<a href="<?=base_url('/recommend_template/outside_add')?>" class="btn btn-success">新增外部撰寫之推薦函</a>
<?php } ?>
</div>
<div class="text-center mb-4">
<?php if (!empty($authority['inside'])){ ?>
<a href="<?=base_url('/recommend_template/inside')?>" class="btn btn-success mr-4">檢視或修改內部撰寫之推薦函</a>
<?php } ?>
<?php if (!empty($authority['outside'])){ ?>
<a href="<?=base_url('/recommend_template/outside')?>" class="btn btn-success">檢視或修改外部撰寫之推薦函</a>
<?php } ?>
</div>
<div class="text-center">
<?php if (!empty($authority['confirm'])){ ?>
<a href="<?=base_url('/recommend_template/confirm')?>" class="btn btn-success mr-4">檢視或修改定案之推薦函</a>
<?php } ?>
</div>
</div>
</div>
</div><file_sep>/application/migrations/036_update_payment_type.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_payment_type extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_payments', [
'type_id' => [
'type' => 'Tinyint',
'constraint' => 2,
'unsigned' => TRUE,
'default' => 1,
'after' => 'price',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_payments', 'type_id');
}
}<file_sep>/application/views/coupon/overview.php
<div class="container">
<h1 class="mb-4"><?= $dealer['company'] ?>貴賓優惠券序號登錄</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">年分/月份</th>
<th class="text-center">優惠券張數</th>
<th class="text-center">首張優惠券序號 </th>
<th class="text-center">末張優惠券序號</th>
<th></th>
</tr>
<?php
if ($coupons) {
foreach ($coupons as $coupon) {
?>
<tr>
<td class="text-center"><?= date('Y年m月', strtotime($coupon['coupon_month'])) ?></td>
<td class="text-center"><?= ($coupon['qty']) ? $coupon['qty'] : '' ?></td>
<td class="text-center"><?= $coupon['first_couponNum'] ?></td>
<td class="text-center"><?= $coupon['last_couponNum'] ?></td>
<td class="text-center">
<div class="btn-group">
<?php if (!empty($authority['edit']) && empty($coupon['receive_confirm']) && strtotime(date('Y-m-01')) <= strtotime($coupon['coupon_month'])){ ?>
<a class="btn btn-warning btn-sm"
href="<?= base_url('/coupon/edit/' . (empty($coupon['id']) ? 'month_'.$coupon['coupon_month'] : $coupon['id'])) ?>">
<i class="fas fa-edit"></i> 貴賓優惠券序號登錄
</a>
<?php } ?>
</div>
</td>
<?php
}
}
?>
</table>
</div><file_sep>/application/models/Retail_model.php
<?php
class Retail_model extends MY_Model{
public $table = 'retail';
public $primary_key = 'rid';
function __construct(){
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
}
}
?>
<file_sep>/application/views/stock/overview.php
<div class="container">
<h1 class="mb-4"><?= $retailer['company'] ?>庫存列表</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">項次</th>
<th class="text-center">貨品編號</th>
<th class="text-center">貨品名稱</th>
<th class="text-center">正常品數量</th>
<th class="text-center">即期品數量</th>
<th class="text-center">過期品數量</th>
<th class="text-center">未標到期日數量</th>
<?php if (!empty($authority['detail'])){ ?>
<th></th>
<?php } ?>
</tr>
<?php
if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td class="text-center"><?= $product['p_num'] ?></td>
<td class="text-center"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
<td class="text-right"><?= $product['stock']['normal']['total'] ?></td>
<td class="text-right"><?= $product['stock']['nearing']['total'] ?></td>
<td class="text-right"><?= $product['stock']['expired']['total'] ?></td>
<td class="text-right"><?= $product['stock']['untag']['total'] ?></td>
<?php if (!empty($authority['detail'])){ ?>
<td class="text-center">
<div class="btn-group" role="group">
<a class="btn btn-info btn-sm" href="<?= base_url('/stock/detail/' . $product_id) ?>">詳細</a>
</div>
</td>
<?php } ?>
<?php
$i++;
}
}
?>
</table>
</div><file_sep>/README.md
# pcart
在Cli中,專案目錄下指令 php index.php migrate version XXX
XXX 為Migration版本號碼,目前到69
Seeder 指令 php index.php seeder all
<file_sep>/application/views/capital/promote/method/advance2.php
<div class="container">
<h1 class="mb-4"><?=$promote['title']?> 滿額折扣設定</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>滿額值</label>
<input type="number" name="limit" class="form-control" required min="1000" max="100000" value="<?= set_value('limit', ($promote_method ? $promote_method['limit'] : '')) ?>" />
</div>
<div class="form-group">
<label>優惠值</label>
<input type="number" name="discount" class="form-control" required min="50" max="10000" value="<?= set_value('discount', ($promote_method ? $promote_method['discount'] : '')) ?>" />
</div>
<div class="form-group">
<label class="font-weight-bold">適用折扣商品</label>
<select id="items" name="items[]" class="form-control" multiple>
<?php foreach ($combos as $combo_id => $combo) { ?>
<option value="c_<?= $combo_id ?>" <?php if (set_value('items', $items) && in_array('c_'.$combo_id, set_value('items', $items))){ echo 'selected';} ?>>[組合商品]<?= $combo['name'] ?></option>
<?php } ?>
<?php foreach ($products as $product_id => $product) { ?>
<option value="p_<?= $product_id ?>" <?php if (set_value('items', $items) && in_array('p_'.$product_id, set_value('items', $items))){ echo 'selected';} ?>><?= $product['pdName']. $product['intro2'] ?></option>
<?php } ?>
</select>
<small>*留空代表全部商品</small>
<input type="hidden" name="discount_type" value="F" />
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/capital_promote_method/overview/' . $promote['id']) ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="送出"/>
</div>
</form>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css"
integrity="<KEY> crossorigin="anonymous"/>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css"
integrity="<KEY> crossorigin="anonymous"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script>
$().ready(function () {
$('#items').select2({
theme: "bootstrap",
multiple: true,
placeholder: '選擇折扣商品'
});
});
</script><file_sep>/application/migrations/058_update_stock_expiry_date.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_stock_expiry_date extends CI_Migration {
public function up()
{
$this->dbforge->add_column('olive_stocks', [
'expired_at' => [
'type' => 'date',
'null' => TRUE,
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_stocks', 'expired_at');
}
}<file_sep>/application/controllers/Capital_level.php
<?php
class Capital_level extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_level_model');
$this->session->set_userdata('return_page', base_url('/capital_level/overview'));
}
public function overview()
{
$total_levels_count = $this->retailer_level_model
->count_rows();
$levels = $this->retailer_level_model
->with_type()
->order_by('retailer_level_type_id', 'asc')
->order_by('code', 'asc')
->paginate(20, $total_levels_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_level', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_level', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_level', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'levels' => $levels,
'pagination' => $this->retailer_level_model->all_pages,
'authority' => $authority,
'title' => '經銷規則',
'view' => 'capital/level/overview',
];
$this->_preload($data);
}
public function add()
{
$this->load->model('retailer_level_type_model');
$level_types = $this->retailer_level_type_model->getTypeSelect();
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_level_type_id', '經銷類別', 'required|integer|in_list[' . implode(',',array_keys($level_types)) . ']');
$this->form_validation->set_rules('code', '代碼', 'required|max_length[200]');
$this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
$this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer');
$this->form_validation->set_rules('monthThreshold', '每月進貨門檻', 'integer');
$this->form_validation->set_rules('guarantee', '保證金', 'required|integer');
if ($this->form_validation->run() !== FALSE) {
$add_data = [
'retailer_level_type_id' => $this->input->post('retailer_level_type_id'),
'code' => $this->input->post('code'),
'discount' => $this->input->post('discount'),
'firstThreshold' => $this->input->post('firstThreshold'),
'monthThreshold' => $this->input->post('monthThreshold'),
'guarantee' => $this->input->post('guarantee'),
'remark' => $this->input->post('remark') ? $this->input->post('remark') : null,
];
$this->retailer_level_model->insert($add_data);
redirect(base_url('/capital_level/overview/'));
}
}
$data = [
'level_types' => $level_types,
'title' => '新增經銷規則',
'view' => 'capital/level/add',
];
$this->_preload($data);
}
public function edit($level_id)
{
$level = $this->retailer_level_model
->with_type()
->get($level_id);
if (!$level_id || !$level) {
show_error('查無經銷規則資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('code', '代碼', 'required|max_length[200]');
$this->form_validation->set_rules('discount', '折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
$this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer');
$this->form_validation->set_rules('monthThreshold', '每月進貨門檻', 'integer');
$this->form_validation->set_rules('guarantee', '保證金', 'required|integer');
if ($this->form_validation->run() !== FALSE) {
$update_data = [
'code' => $this->input->post('code'),
'discount' => $this->input->post('discount'),
'firstThreshold' => $this->input->post('firstThreshold'),
'monthThreshold' => $this->input->post('monthThreshold'),
'guarantee' => $this->input->post('guarantee'),
'remark' => $this->input->post('remark') ? $this->input->post('remark') : null,
];
$this->retailer_level_model->update($update_data, ['id' => $level_id]);
// if (!empty($this->dealer['level']) && $this->dealer['level']['id'] == $level_id) {
// $this->dealer['level']['discount'] = $this->input->post('discount');
// $this->dealer['level']['discount_text'] = $this->input->post('discount') . '%';
// $this->dealer['level']['firstThreshold'] = $this->input->post('firstThreshold') ? $this->input->post('firstThreshold') : null;
// $this->dealer['level']['monthThreshold'] = $this->input->post('monthThreshold') ? $this->input->post('monthThreshold') : null;
// $this->session->set_userdata('dealer', $this->dealer);
// }
redirect(base_url('/capital_level/overview/'));
}
}
$data = [
'level' => $level,
'title' => '編輯經銷規則',
'view' => 'capital/level/edit',
];
$this->_preload($data);
}
public function cancel($level_id)
{
$level = $this->retailer_level_model
->with_type()
->get($level_id);
if (!$level_id || !$level) {
show_error('查無經銷規則資料');
}
$this->load->model('retailer_model');
$retailers = $this->retailer_model
->where('retailer_level_id', $level_id)
->get_all();
if ($retailers){
$str = '';
foreach ($retailers as $retailer){
$str .= $retailer['company'].', ';
}
show_error('此經銷規則已有經銷商使用,不能刪除,請先修改以下經銷商(' . $str . ')');
}
$this->retailer_level_model->delete($level_id);
redirect(base_url('/capital_level/overview/'));
}
}
?><file_sep>/application/controllers/Db.php
<?php
class Db extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
}
public function index()
{
$results = [];
if ($this->input->post()) {
$this->form_validation->set_rules('query', 'SQL', 'required');
if ($this->form_validation->run() !== FALSE) {
$query = $this->db->query($this->input->post('query'));
if (is_object($query) && $query->num_rows() > 0) {
$results = $query->result_array();
} elseif ($query == '1') {
$results[] = '成功';
}
}
}
$data = [
'results' => $results,
'view' => 'db',
];
$this->_preload($data);
}
public function info()
{
echo phpinfo();
}
}
?><file_sep>/application/views/capital/retailer/group/overview.php
<div class="container">
<h1 class="mb-4"><?=$role['title']?>群組列表
<?php if (!empty($authority['add'])){ ?>
<a href="<?= base_url('/capital_retailer_group/add/' . $id) ?>" class="btn btn-success float-right"><i
class="far fa-plus-square"></i> 新增群組</a>
<?php } ?>
</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">群組名稱</th>
<th></th>
</tr>
<?php
if ($groups) {
foreach ($groups as $group) {
?>
<tr>
<td class="text-center"><?= $group['title'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['edit'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/capital_retailer_group/edit/' . $group['id']) ?>">編輯</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
}
?>
</table>
</div><file_sep>/application/migrations/004_add_confirm.php
<?php
//經銷商訂貨單聯絡資訊
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_confirm extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'confirm_type' => [
'type' => 'VARCHAR',
'constraint' => 30,
],
'confirm_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'audit_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'audit' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_confirms');
}
public function down()
{
$this->dbforge->drop_table('olive_confirms');
}
}<file_sep>/application/views/transfer/transfer.php
<div class="container">
<h1 class="mb-4">出貨單轉單</h1>
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<form method="post">
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">轉單對象</label>
<div class="col-sm-10">
<select id="transfer_retailer_id" name="transfer_retailer_id" class="form-control" required>
<option value=""></option>
<?php foreach ($shipout_retailers as $retailer_id => $retailer) { ?>
<option value="<?= $retailer_id ?>"><?= $retailer['company'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group text-center">
<a class="btn btn-secondary mr-2" href="<?= base_url('/transfer/overview/') ?>">取消</a>
<input type="submit" class="btn btn-success" value="確認轉單"/>
</div>
</form>
</div><file_sep>/application/controllers/Capital_promote.php
<?php
class Capital_promote extends MY_Controller
{
protected $dealer;
protected $customer_type;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('promote_model');
$this->customer_type = [
null => "全部會員",
1 => "特定時間加入之新會員",
2 => "特定時間之舊有會員已轉新會員",
3 => "員工",
];
$this->session->set_userdata('return_page', base_url('/capital_promote/overview'));
}
public function overview()
{
$total_promotes_count = $this->promote_model
->count_rows();
$promotes = $this->promote_model
->order_by('start_at', 'desc')
->paginate(20, $total_promotes_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_promote', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_promote_method', 'overview')){
$authority['method'] = true;
}
if ($this->authentic->authority('capital_promote', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_promote', 'cancel')){
$authority['cancel'] = true;
}
$this->load->helper('data_format');
$data = [
'customer_type' => $this->customer_type,
'promotes' => $promotes,
'pagination' => $this->promote_model->all_pages,
'authority' => $authority,
'title' => '優惠活動列表',
'view' => 'capital/promote/overview',
];
$this->_preload($data);
}
public function add()
{
if ($this->input->post()) {
$this->form_validation->set_rules('title', '活動名稱', 'required|max_length[100]');
$this->form_validation->set_rules('start_at', '活動開始', 'required|valid_date');
$this->form_validation->set_rules('end_at', '活動結束', 'required|valid_date');
$this->form_validation->set_rules('customer_type', '適用對象', 'integer|in_list[' . implode(',',array_keys($this->customer_type)) . ']');
$this->form_validation->set_rules('customer_limit', '可享用之優惠次數', 'integer');
$this->form_validation->set_rules('customer_start_at', '適用對象加入開始時間', 'valid_date');
$this->form_validation->set_rules('customer_end_at', '適用對象加入結束時間', 'valid_date');
$this->form_validation->set_rules('go_with_member', '會員優惠同時使用', 'integer');
$this->form_validation->set_rules('go_with_coupon', '貴賓優惠券同時使用', 'integer');
if ($this->form_validation->run() !== FALSE) {
$exclude_retailers = (array)$this->input->post('exclude_retailers');
$insert_options = [
'title' => $this->input->post('title'),
'start_at' => $this->input->post('start_at'),
'end_at' => $this->input->post('end_at'),
'exclude_retailers' => $exclude_retailers ? implode(',', $exclude_retailers) : null,
'customer_type' => $this->input->post('customer_type') ? $this->input->post('customer_type') : null,
'customer_limit' => $this->input->post('customer_limit') ? $this->input->post('customer_limit') : null,
'customer_start_at' => null,
'customer_end_at' => null,
'go_with_member' => empty($this->input->post('go_with_member')) ? 0 : 1,
'go_with_coupon' => empty($this->input->post('go_with_coupon')) ? 0 : 1,
];
if (in_array($this->input->post('customer_type'), [1, 2])){
$insert_options['customer_start_at'] = $this->input->post('customer_start_at') ? $this->input->post('customer_start_at') : null;
$insert_options['customer_end_at'] = $this->input->post('customer_end_at') ? $this->input->post('customer_end_at') : null;
}
$promote_id = $this->promote_model->insert($insert_options);
redirect(base_url('/capital_promote_method/add/' . $promote_id));
}
}
$this->load->helper('form');
$retailers = $this->retailer_model
->order_by('retailer_role_id', 'asc')
->order_by('id', 'desc')
->get_all();
$data = [
'customer_type' => $this->customer_type,
'retailers' => $retailers,
'title' => '新增優惠活動',
'view' => 'capital/promote/add',
];
$this->_preload($data);
}
public function edit($promote_id)
{
$promote = $this->promote_model
->get($promote_id);
if (!$promote_id || !$promote) {
show_error('查無優惠活動資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('title', '活動名稱', 'required|max_length[100]');
$this->form_validation->set_rules('start_at', '活動開始', 'required|valid_date');
$this->form_validation->set_rules('end_at', '活動結束', 'required|valid_date');
$this->form_validation->set_rules('customer_type', '適用對象', 'integer|in_list[' . implode(',',array_keys($this->customer_type)) . ']');
$this->form_validation->set_rules('customer_limit', '可享用之優惠次數', 'integer');
$this->form_validation->set_rules('customer_start_at', '適用對象加入開始時間', 'valid_date');
$this->form_validation->set_rules('customer_end_at', '適用對象加入結束時間', 'valid_date');
$this->form_validation->set_rules('go_with_member', '會員優惠同時使用', 'integer');
$this->form_validation->set_rules('go_with_coupon', '貴賓優惠券同時使用', 'integer');
if ($this->form_validation->run() !== FALSE) {
$exclude_retailers = (array)$this->input->post('exclude_retailers');
$update_options = [
'title' => $this->input->post('title'),
'start_at' => $this->input->post('start_at'),
'end_at' => $this->input->post('end_at'),
'exclude_retailers' => $exclude_retailers ? implode(',', $exclude_retailers) : null,
'customer_type' => $this->input->post('customer_type') ? $this->input->post('customer_type') : null,
'customer_limit' => $this->input->post('customer_limit') ? $this->input->post('customer_limit') : null,
'customer_start_at' => null,
'customer_end_at' => null,
'go_with_member' => empty($this->input->post('go_with_member')) ? 0 : 1,
'go_with_coupon' => empty($this->input->post('go_with_coupon')) ? 0 : 1,
];
if (in_array($this->input->post('customer_type'), [1, 2])){
$update_options['customer_start_at'] = $this->input->post('customer_start_at') ? $this->input->post('customer_start_at') : null;
$update_options['customer_end_at'] = $this->input->post('customer_end_at') ? $this->input->post('customer_end_at') : null;
}
$this->promote_model->update($update_options, ['id' => $promote_id]);
redirect(base_url('/capital_promote/overview/'));
}
}
$retailers = $this->retailer_model
->order_by('retailer_role_id', 'asc')
->order_by('id', 'desc')
->get_all();
$promote['exclude_retailers'] = explode(',', $promote['exclude_retailers']);
$data = [
'customer_type' => $this->customer_type,
'retailers' => $retailers,
'promote' => $promote,
'title' => '編輯優惠活動',
'view' => 'capital/promote/edit',
];
$this->_preload($data);
}
public function cancel($promote_id)
{
$promote = $this->promote_model
->get($promote_id);
if (!$promote_id || !$promote) {
show_error('查無優惠活動資料');
}
$this->promote_model->delete($promote_id);
redirect(base_url('/capital_promote/overview/'));
}
}
?><file_sep>/application/controllers/Recommend_template.php
<?php
class Recommend_template extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('recommend_template_model');
$this->session->set_userdata('return_page', base_url('/recommend_template/overview'));
}
public function index()
{
//權限設定
$authority = array();
if ($this->authentic->authority('recommend_template', 'inside_add')){
$authority['inside_add'] = true;
}
if ($this->authentic->authority('recommend_template', 'outside_add')){
$authority['outside_add'] = true;
}
if ($this->authentic->authority('recommend_template', 'inside')){
$authority['inside'] = true;
}
if ($this->authentic->authority('recommend_template', 'outside')){
$authority['outside'] = true;
}
if ($this->authentic->authority('recommend_template', 'confirm')){
$authority['confirm'] = true;
}
$data = [
'authority' => $authority,
'title' => '推薦函之增修',
'view' => 'recommend_template/index',
];
$this->_preload($data);
}
public function confirm()
{
$total_templates_count = $this->recommend_template_model
->where('isConfirmed', 1)
->count_rows();
$templates = $this->recommend_template_model
->where('isConfirmed', 1)
->order_by('id', 'desc')
->paginate(20, $total_templates_count);
//權限設定
$authority = array();
if ($this->authentic->authority('recommend_template', 'confirm_edit')){
$authority['edit'] = true;
}
$data = [
'templates' => $templates,
'pagination' => $this->recommend_template_model->all_pages,
'authority' => $authority,
'title' => '檢視或修改定案之推薦函',
'view' => 'recommend_template/confirm/index',
];
$this->_preload($data);
}
public function inside()
{
$total_templates_count = $this->recommend_template_model
->where('type', 'I')
->where('isConfirmed', 0)
->count_rows();
$templates = $this->recommend_template_model
->where('type', 'I')
->where('isConfirmed', 0)
->order_by('id', 'desc')
->paginate(20, $total_templates_count);
//權限設定
$authority = array();
if ($this->authentic->authority('recommend_template', 'inside_add')){
$authority['add'] = true;
}
if ($this->authentic->authority('recommend_template', 'inside_edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('recommend_template', 'confirming')){
$authority['confirming'] = true;
}
$data = [
'templates' => $templates,
'pagination' => $this->recommend_template_model->all_pages,
'authority' => $authority,
'title' => '檢視或修改內部撰寫之推薦函',
'view' => 'recommend_template/inside/index',
];
$this->_preload($data);
}
public function outside()
{
$total_templates_count = $this->recommend_template_model
->where('type', 'O')
->where('isConfirmed', 0)
->count_rows();
$templates = $this->recommend_template_model
->where('type', 'O')
->where('isConfirmed', 0)
->order_by('id', 'desc')
->paginate(20, $total_templates_count);
//權限設定
$authority = array();
if ($this->authentic->authority('recommend_template', 'outside_add')){
$authority['add'] = true;
}
if ($this->authentic->authority('recommend_template', 'outside_edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('recommend_template', 'confirming')){
$authority['confirming'] = true;
}
$data = [
'templates' => $templates,
'pagination' => $this->recommend_template_model->all_pages,
'authority' => $authority,
'title' => '檢視或修改外部撰寫之推薦函',
'view' => 'recommend_template/outside/index',
];
$this->_preload($data);
}
public function confirm_edit($template_id)
{
$template = $this->recommend_template_model
->where('isConfirmed', 1)
->get($template_id);
if (!$template_id || !$template) {
show_error('查無推薦函資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('content', '內容', 'required');
if ($this->form_validation->run() !== FALSE) {
$this->recommend_template_model->update(['content' => $this->input->post('content')], ['id' => $template_id]);
redirect(base_url('/recommend_template/confirm'));
}
}
$data = [
'template' => $template,
'title' => '修改定案之推薦函',
'view' => 'recommend_template/confirm/edit',
];
$this->_preload($data);
}
public function inside_add()
{
if ($this->input->post()) {
$this->form_validation->set_rules('content', '內容', 'required');
if ($this->form_validation->run() !== FALSE) {
$this->recommend_template_model->insert(
[
'type' => 'I',
'content' => $this->input->post('content')
]
);
if ($_POST['continue_add']){
redirect(base_url('/recommend_template/inside_add'), 'refresh');
} else {
redirect(base_url('/recommend_template'));
}
}
}
$data = [
'title' => '新增內部撰寫之推薦函',
'view' => 'recommend_template/inside/add',
];
$this->_preload($data);
}
public function inside_edit($template_id)
{
$template = $this->recommend_template_model
->where('type', 'I')
->where('isConfirmed', 0)
->get($template_id);
if (!$template_id || !$template) {
show_error('查無推薦函資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('content', '內容', 'required');
if ($this->form_validation->run() !== FALSE) {
$this->recommend_template_model->update(['content' => $this->input->post('content')], ['id' => $template_id]);
redirect(base_url('/recommend_template/inside'));
}
}
$data = [
'template' => $template,
'title' => '修改定案之推薦函',
'view' => 'recommend_template/inside/edit',
];
$this->_preload($data);
}
public function outside_add()
{
if ($this->input->post()) {
$this->form_validation->set_rules('content', '內容', 'required');
if ($this->form_validation->run() !== FALSE) {
$this->recommend_template_model->insert(
[
'type' => 'O',
'content' => $this->input->post('content')
]
);
if ($_POST['continue_add']){
redirect(base_url('/recommend_template/outside_add'), 'refresh');
} else {
redirect(base_url('/recommend_template'));
}
}
}
$data = [
'title' => '新增外部撰寫之推薦函',
'view' => 'recommend_template/outside/add',
];
$this->_preload($data);
}
public function outside_edit($template_id)
{
$template = $this->recommend_template_model
->where('type', 'O')
->where('isConfirmed', 0)
->get($template_id);
if (!$template_id || !$template) {
show_error('查無推薦函資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('content', '內容', 'required');
if ($this->form_validation->run() !== FALSE) {
$this->recommend_template_model->update(['content' => $this->input->post('content')], ['id' => $template_id]);
redirect(base_url('/recommend_template/outside'));
}
}
$data = [
'template' => $template,
'title' => '修改外部撰寫之推薦函',
'view' => 'recommend_template/outside/edit',
];
$this->_preload($data);
}
public function confirming($template_id)
{
$template = $this->recommend_template_model
->where('isConfirmed', 0)
->get($template_id);
if (!$template_id || !$template) {
show_error('查無推薦函資料');
}
$this->recommend_template_model->update(['isConfirmed' => 1], ['id' => $template_id]);
redirect(base_url('/recommend_template'));
}
}
?><file_sep>/application/views/capital/retailer/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增單位</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>單位類型</label>
<?php
echo form_dropdown('retailer_role_id', $roles, set_value('retailer_role_id'), 'class="form-control"');
?>
</div>
<div class="form-group">
<label>單位名稱</label>
<input name="company" class="form-control" value="<?= set_value('company') ?>" required />
</div>
<div class="form-group">
<label>單位抬頭</label>
<input name="invoice_title" class="form-control" value="<?= set_value('invoice_title') ?>"/>
</div>
<div class="form-group">
<label>收款銀行</label>
<input name="bank" class="form-control" value="<?= set_value('bank') ?>" maxlength="100" />
</div>
<div class="form-group">
<label>分行名</label>
<input name="bank_branch" class="form-control" value="<?= set_value('bank_branch') ?>" maxlength="100" />
</div>
<div class="form-group">
<label>收款戶名</label>
<input name="bank_account_title" class="form-control" value="<?= set_value('bank_account_title') ?>" maxlength="100" />
</div>
<div class="form-group">
<label>收款帳戶</label>
<input name="bank_account" class="form-control" value="<?= set_value('bank_account') ?>" maxlength="100" />
</div>
<div class="form-group">
<label>統一編號</label>
<input name="identity" class="form-control"
value="<?= set_value('identity') ?>" required />
</div>
<div class="form-group">
<label>聯絡電話1</label>
<input name="phone" class="form-control"
value="<?= set_value('phone', $dealer['phone']) ?>" required />
</div>
<div class="form-group">
<label>聯絡電話2</label>
<input name="altPhone" class="form-control" value="<?= set_value('altPhone') ?>"/>
</div>
<div class="form-group">
<label>聯絡地址</label>
<input name="address" class="form-control" value="<?= set_value('address') ?>" required />
</div>
<div class="form-group">
<label>首次進貨門檻</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" name="firstThreshold" class="form-control text-right" value="<?= set_value('firstThreshold') ?>"/>
</div>
</div>
<div class="form-group">
<label>每月進貨門檻</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" name="purchaseThreshold" class="form-control text-right" value="<?= set_value('purchaseThreshold') ?>"/>
</div>
</div>
<div class="form-group">
<label>輔銷單位</label>
<?php
echo form_dropdown('sales_retailer_id', ['' => ''] + $retailer_selects, set_value('sales_retailer_id'), 'class="form-control"');
?>
</div>
<div class="form-group">
<label>輔銷人</label>
<?php
echo form_dropdown('sales_dealer_id', ['' => ''] + $dealer_selects, set_value('sales_dealer_id'), 'class="form-control"');
?>
</div>
<div class="form-group">
<label>是否管理庫存</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="hasStock" id="hasStock_1"
value="1"<?= set_value('hasStock') == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="hasStock_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="hasStock" id="hasStock_0"
value="0"<?= set_value('hasStock') != '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="hasStock_0">否</label>
</div>
</div>
</div>
<div class="form-group">
<label>是否加總總倉庫存</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="totalStock" id="totalStock_1"
value="1"<?= set_value('totalStock') == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="totalStock_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="totalStock" id="totalStock_0"
value="0"<?= set_value('totalStock') != '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="totalStock_0">否</label>
</div>
</div>
</div>
<div class="form-group">
<label>散裝進貨資格</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_1"
value="1"<?= set_value('isAllowBulk') == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="isAllowBulk_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="isAllowBulk" id="isAllowBulk_0"
value="0"<?= set_value('isAllowBulk') != '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="isAllowBulk_0">否</label>
</div>
</div>
</div>
<div class="form-group">
<label>出貨期限</label>
<input type="number" name="eta_days" class="form-control" value="<?= set_value('eta_days') ?>" />
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_retailer/overview/')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/capital/combo/add.php
<div class="container">
<h1 class="mb-4">新增商品組合</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">組合名稱</label>
<input name="name" class="form-control" value="<?= set_value('name') ?>" required/>
</div>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價(含稅)</th>
<th>數量</th>
<th>組合分攤單價</th>
</tr>
<?php if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td><?= $product['p_num'] ?></td>
<td>
<?= $product['pdName'] ?> <?= $product['intro2'] ?>
<?php if ($product['picture']) { ?>
<a class="show_picture" data-toggle="tooltip"
title="<img src='<?= $product['picture'] ?>' />">
<i class="far fa-images"></i>
</a>
<?php } ?>
</td>
<td><?= $product['pdCash'] ?></td>
<td>
<input type="number" name="items[<?= $product_id ?>][qty]"
min="1" class="itemQty form-control text-right"
value="<?= set_value('items[' . $product_id . '][qty]') ?>"
style="width: 120px;"
/>
</td>
<td>
<input type="number" name="items[<?= $product_id ?>][price]"
min="0" class="itemPrice form-control text-right"
value="<?= set_value('items[' . $product_id . '][price]') ?>"
style="width: 120px;"
/>
</td>
</tr>
<?php
$i++;
}
}
?>
<tr>
<td colspan="5" class="text-right font-weight-bold">組合總價</td>
<td id="total_price" class="text-right font-weight-bold"></td>
</tr>
</table>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/capital_combo/overview/') ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
<script>
$().ready(function () {
calc_total();
$('a.show_picture').tooltip({
animated: 'fade',
placement: 'top',
html: true
});
$('input.itemPrice').change(function () {
calc_total();
});
$('input.itemQty').change(function () {
calc_total();
});
function calc_total() {
var total = 0;
$('form input.itemPrice').each(function () {
var item = $(this).parents('tr');
var itemPrice = parseInt($(this).val()) || 0;
var itemQty = parseInt(item.find('input.itemQty').val()) || 0;
total += itemPrice * itemQty;
});
$('#total_price').text('$' + numberWithCommas(total));
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$("form").find('input[type="submit"]').click(function (e) {
$.each($('.itemPrice'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('.itemQty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
});
});
</script><file_sep>/application/migrations/033_update_purchase.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_purchase extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_purchases', [
'transfer_id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
'after' => 'id',
],
'isPayConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'paid_at',
],
'isShipConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'shipped_at',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_purchases', 'transfer_id');
$this->dbforge->drop_column('olive_purchases', 'isPayConfirmed');
$this->dbforge->drop_column('olive_purchases', 'isShipConfirmed');
}
}<file_sep>/application/models/Promote_use_model.php
<?php
class Promote_use_model extends MY_Model
{
public $table = 'olive_promote_uses';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['promote'] = array('foreign_model' => 'Promote_model', 'foreign_table' => 'olive_promotes', 'foreign_key' => 'id', 'local_key' => 'promote_id');
$this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'id', 'local_key' => 'customer_id');
}
public function getUseTime($promote_id, $customer_id)
{
return $this
->where('promote_id', $promote_id)
->where('customer_id', $customer_id)
->count_rows();
}
}
?>
<file_sep>/application/controllers/Guest.php
<?php
class Guest extends MY_Controller
{
protected $guest;
public function __construct()
{
parent::__construct();
$this->guest = $this->session->userdata('guest');
if (!$this->guest) {
redirect(base_url('/auth/register'));
}
$this->load->model('product_model');
$this->load->model('dealer_model');
$this->load->model('retailer_model');
}
public function level()
{
$this->load->model('retailer_level_type_model');
$this->load->model('retailer_qualification_model');
$_retailer_level_types = $this->retailer_level_type_model
->with_levels()
->get_all();
$retailer_level_types = [];
foreach ($_retailer_level_types as $retailer_level_type){
$retailer_levels = [];
foreach ($retailer_level_type['levels'] as $l){
$qualification = $this->retailer_qualification_model
->where('retailer_id', $this->guest['sales_dealer']['retailer_id'])
->where('retailer_level_id', $l['id'])
->get();
if ($qualification){
if ($l['discount'] < 60){
$l['commission_rate'] = 2;
} elseif ($l['discount'] < 75){
$l['commission_rate'] = 3;
} else {
$l['commission_rate'] = 0;
}
$retailer_levels[] = $l;
}
}
$retailer_level_type['levels'] = $retailer_levels;
$retailer_level_types[$retailer_level_type['type']] = $retailer_level_type;
}
if ($this->input->post()) {
$this->form_validation->set_rules('type', '經銷商類別', 'trim|required|in_list[' . implode(',', array_keys($retailer_level_types)) . ']');
if ($this->form_validation->run() !== FALSE) {
$type = $this->input->post('type');
if (empty($retailer_level_types[$type]['levels'])){
show_error('經銷商規劃中,敬請期待');
}
$levels = [];
foreach ($retailer_level_types[$type]['levels'] as $l) {
$l['title'] = $retailer_level_types[$type]['title'] . ' ' . $l['code'];
$l['isAllowBulk'] = 0;
$levels[$l['id']] = $l;
}
$this->load->model('retailer_model');
$level = [
'id' => null,
'discount' => 100,
];
$this->guest['levels'] = $levels;
$this->guest['retailer_level_type'] = [
'id' => $retailer_level_types[$type]['id'],
'type' => $retailer_level_types[$type]['type'],
'title' => $retailer_level_types[$type]['title'],
];
$this->guest['level'] = $level;
$this->session->set_userdata('guest', $this->guest);
redirect(base_url('/guest/cart'));
}
}
$data = [
'retailer_level_types' => $retailer_level_types,
'title' => '經銷商身份類別選擇',
'view' => 'guest/level',
];
$this->_preload($data, 'guest');
}
public function cart()
{
if (empty($this->guest['levels'])) {
show_error('經銷商規劃中,敬請期待');
}
if (empty($this->guest['retailer_level_type'])) {
show_error('您尚未選擇經銷類別');
}
$this->load->model('product_permission_model');
$products = $this->product_permission_model->getPermissionProducts();
if (!$products){
show_error('目前尚無商品可以採購');
}
if ($this->input->post()) {
$this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('monthThreshold', '每月進貨門檻', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('isAllowBulk', '散裝進貨資格', 'integer|in_list[0,1]');
$this->form_validation->set_rules('discount', '進貨折扣', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
$this->form_validation->set_rules('retailer_level_id', '經銷商類別', 'required|integer|in_list[' . implode(',', array_keys($this->guest['levels'])) . ']');
$this->form_validation->set_rules('items[][qty]', '訂購數量', 'callback_check_total['. json_encode(['guest_level' => $this->guest['levels'][$this->input->post('retailer_level_id')], 'retailer_level_type' => $this->guest['retailer_level_type'], 'retailer_group_id' => $this->guest['sales_dealer']['retailer_group_id'], 'products' => $products, 'items' => $this->input->post('items'), 'discount' => $this->input->post('discount'), 'isAllowBulk' => $this->input->post('isAllowBulk'), 'firstThreshold' => $this->input->post('firstThreshold')]) .']');
if ($this->form_validation->run() !== FALSE) {
$this->guest['purchase']['cart'] = [];
$items = (array)$this->input->post('items');
$cart = [];
$subtotal = 0;
$total = 0;
foreach ($items as $product_id => $item) {
if ($item['qty'] > 0) {
$_data = [
'id' => $product_id,
'qty' => $item['qty'],
'price' => $products[$product_id]['pdCash'],
'name' => $products[$product_id]['pdName'] . ' ' . $products[$product_id]['intro2'],
'pKind' => $products[$product_id]['pKind'],
'p_num' => $products[$product_id]['p_num'],
'ctName' => $products[$product_id]['product_kind']['ctName'], //分類
'boxAmount' => $products[$product_id]['boxAmount'],
];
$subtotal += $item['qty'] * $products[$product_id]['pdCash'];
$cart[] = $_data;
}
}
$this->guest['level'] = $this->guest['levels'][$this->input->post('retailer_level_id')];
if ($this->guest['sales_dealer']['retailer_group_id'] == 4){ //總監
$this->guest['level']['discount'] = $this->input->post('discount');
$this->guest['level']['isAllowBulk'] = $this->input->post('isAllowBulk');
$this->guest['level']['firstThreshold'] = $this->input->post('firstThreshold');
$this->guest['level']['monthThreshold'] = $this->input->post('monthThreshold');
}
foreach ($cart as $item) {
$discount = $this->guest['level']['discount'];
$total += floor($item['price'] * $discount / 100) * $item['qty'];
}
$this->guest['purchase'] = [
'cart' => $cart,
'subtotal' => $subtotal,
'total' => $total,
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
];
if ($this->guest['level']['discount'] > 55) {
$this->guest['admin_check_discount'] = true;
}
switch ($this->guest['sales_dealer']['retailer_role_id']){
case 3: //門市
if ($this->guest['level']['discount'] > 55) {
$this->guest['sales_retailer'] = $this->retailer_model->get($this->guest['sales_dealer']['retailer_id']);
} else {
$this->guest['sales_retailer'] = $this->retailer_model->get(2);
}
break;
case 5: //經銷商
if ($this->guest['level']['discount'] > 55) {
$this->guest['sales_retailer'] = $this->retailer_model->get($this->guest['sales_dealer']['sales_retailer']['id']);
} else {
$this->guest['sales_retailer'] = $this->retailer_model->get(2);
}
break;
default: //總經銷
$this->guest['sales_retailer'] = $this->retailer_model->get(2);
break;
}
$this->session->set_userdata('guest', $this->guest);
if ($this->guest['admin_check_discount']) {
redirect(base_url('/guest/info'));
} else {
redirect(base_url('/guest/adminCheck'));
}
}
}
foreach ($this->guest['purchase']['cart'] as $item) {
$products[$item['id']]['qty'] = $item['qty'];
}
$data = [
'guest' => $this->guest,
'products' => $products,
'title' => '訂貨單',
'view' => 'guest/cart',
];
$this->_preload($data, 'guest');
}
public function check_total($i, $params)
{
$params = json_decode($params, true);
$guest_level = $params['guest_level'];
$retailer_level_type = $params['retailer_level_type'];
$retailer_group_id = $params['retailer_group_id'];
$discount = $params['discount'];
$isAllowBulk = empty($params['isAllowBulk']) ? 0 : 1;
$firstThreshold = $params['firstThreshold'];
$products = $params['products'];
$items = $params['items'];
$subtotal = 0;
$error = '';
if ($retailer_group_id == 4){ //總監
$guest_level['discount'] = $discount;
$guest_level['firstThreshold'] = $firstThreshold;
$guest_level['isAllowBulk'] = $isAllowBulk;
}
$enableStep = $guest_level['isAllowBulk'] ? false : true;
foreach ($items as $product_id => $item) {
if (!isset($products[$product_id])){
$error = '輸入的貨品有誤';
break;
}
$step = $enableStep ? $products[$product_id]['boxAmount'] : 1;
if ($item['qty'] % $step){
$error = '輸入的貨品數量必須為包裝數量倍數';
break;
}
$subtotal += $item['qty'] * $products[$product_id]['pdCash'];
}
if (!$error) {
if ($subtotal < $guest_level['firstThreshold']) {
$error = '未超過首次進貨門檻,請見訂貨規則';
}
}
if (!$error){
return true;
} else {
$this->form_validation->set_message('check_total', $error);
return false;
}
}
public function adminCheck()
{
if (empty($this->guest['levels'])) {
show_error('經銷商規劃中,敬請期待');
}
if (empty($this->guest['retailer_level_type'])) {
show_error('您尚未選擇經銷類別');
}
if (!$this->guest['purchase']['cart']) {
show_error('您尚未選購商品');
}
if (!$this->guest['sales_retailer']) {
redirect(base_url('/guest/cart'));
}
if ($this->guest['admin_check_discount']) {
redirect(base_url('/guest/info'));
}
if ($this->input->post()) {
$this->form_validation->set_rules('account', '總監代號', 'trim|required');
$this->form_validation->set_rules('password', '密碼', 'trim|required|callback_check_authentic');
if ($this->form_validation->run() !== FALSE) {
$this->guest['admin_check_discount'] = true;
$this->session->set_userdata('guest', $this->guest);
redirect(base_url('/guest/info'));
}
}
$data = [
'title' => '總監登入確認',
'view' => 'guest/admin_check_login',
];
$this->_preload($data, 'guest');
}
public function check_authentic($password)
{
$password = $this->authentic->_mix($password);
$result = $this->dealer_model
->where('account', $this->input->post('account'))
->where('password', $password)
->get();
if ($result) {
return true;
} else {
$this->form_validation->set_message('check_authentic','您輸入的帳號密碼錯誤,請重新確認');
return false;
}
}
public function info()
{
if (empty($this->guest['levels'])) {
show_error('經銷商規劃中,敬請期待');
}
if (empty($this->guest['retailer_level_type'])) {
show_error('您尚未選擇經銷類別');
}
if (!$this->guest['purchase']['cart']) {
show_error('您尚未選購商品');
}
if (!$this->guest['sales_retailer']) {
redirect(base_url('/guest/cart'));
}
if (!$this->guest['admin_check_discount']) {
redirect(base_url('/guest/adminCheck'));
}
//確認下單
if ($this->input->post()) {
$this->guest['retailer']['account'] = $this->input->post('account');
$this->guest['retailer']['company'] = $this->input->post('company');
$this->guest['retailer']['identity'] = $this->input->post('identity');
$this->guest['retailer']['contact'] = $this->input->post('contact');
$this->guest['retailer']['gender'] = $this->input->post('gender');
$this->guest['retailer']['phone'] = $this->input->post('phone');
$this->guest['retailer']['altPhone'] = $this->input->post('altPhone');
$this->guest['retailer']['address'] = $this->input->post('address');
$this->guest['purchase']['memo'] = $this->input->post('memo') ? $this->input->post('memo') : null;
$this->session->set_userdata('guest', $this->guest);
if (!isset($_POST['checkout'])) {
redirect(base_url('/guest/cart'));
} else { //結帳
$this->form_validation->set_rules('account', '經銷商帳號', 'required|alpha_numeric|min_length[3]|max_length[10]|valid_dealer_account');
$this->form_validation->set_rules('company', '經銷商名稱', 'required|max_length[20]');
$this->form_validation->set_rules('identity', '身份證字號/統一編號', 'required|max_length[10]');
$this->form_validation->set_rules('contact', '經銷商代表人姓名', 'required|max_length[20]');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
$this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
$this->form_validation->set_rules('address', '送貨地址', 'required|max_length[100]');
$this->form_validation->set_rules('password', '密碼', 'required|min_length[6]');
$this->form_validation->set_rules('password_confirm', '確認密碼', 'required|min_length[6]|matches[password]');
if ($this->form_validation->run() !== FALSE) {
$this->load->model('purchase_model');
$this->load->model('purchase_item_model');
$password = $this->input->post('password');
$retailer_id = $this->retailer_model->insert([
'sales_retailer_id' => $this->guest['sales_retailer']['id'],
'sales_dealer_id' => $this->guest['sales_dealer']['id'],
'retailer_role_id' => 5, //經銷商
'retailer_level_id' => $this->guest['level']['id'],
'company' => $this->guest['retailer']['company'],
'invoice_title' => $this->guest['retailer']['company'],
'identity' => $this->guest['retailer']['identity'],
'phone' => $this->guest['retailer']['phone'],
'altPhone' => $this->guest['retailer']['altPhone'],
'address' => $this->guest['retailer']['address'],
'firstThreshold' => $this->guest['level']['firstThreshold'],
'purchaseThreshold' => $this->guest['level']['monthThreshold'],
'eta_days' => 15,
'hasStock' => 1,
'isAllowBulk' => $this->guest['level']['isAllowBulk'],
]);
$this->load->model('retailer_group_model');
$retailer_group = $this->retailer_group_model
->where('retailer_role_id', 5)
->where('retailer_level_type_id', $this->guest['level']['retailer_level_type_id'])
->get();
$dealer_id = $this->dealer_model->insert([
'retailer_id' => $retailer_id,
'retailer_group_id' => empty($retailer_group['id']) ? null : $retailer_group['id'],
'account' => $this->guest['retailer']['account'],
'password' => $this->authentic->_mix($password),
'name' => $this->guest['retailer']['contact'],
'gender' => $this->guest['retailer']['gender'],
]);
$this->retailer_model->update(['contact_dealer_id' => $dealer_id], ['id' => $retailer_id]);
$this->load->model('retailer_relationship_model');
$relationships = [
[
'relation_type' => 'shipout',
'retailer_id' => $retailer_id,
'relation_retailer_id' => $this->guest['sales_retailer']['id'],
'discount' => $this->guest['level']['discount'],
],
[
'relation_type' => 'shipin',
'retailer_id' => $retailer_id,
'relation_retailer_id' => $this->guest['sales_retailer']['id'],
'alter_retailer_id' => $retailer_id,
],
[
'relation_type' => 'invoice',
'retailer_id' => $retailer_id,
'relation_retailer_id' => $this->guest['sales_retailer']['id'],
'alter_retailer_id' => $retailer_id,
],
[
'relation_type' => 'invoice_send',
'retailer_id' => $retailer_id,
'relation_retailer_id' => $retailer_id,
],
[
'relation_type' => 'supervisor',
'retailer_id' => $retailer_id,
'relation_retailer_id' => $this->guest['sales_retailer']['id'],
]
];
if ($this->guest['sales_dealer']['retailer_id'] != $this->guest['sales_retailer']['id']){
$rows = $this->retailer_relationship_model
->where('relation_type', 'supervisor')
->where('retailer_id', $this->guest['sales_dealer']['retailer_id'])
->where('relation_retailer_id', $this->guest['sales_retailer']['id'])
->count_rows();
if (!$rows) {
$relationships[] = [
'relation_type' => 'supervisor',
'retailer_id' => $this->guest['sales_dealer']['retailer_id'],
'relation_retailer_id' => $this->guest['sales_retailer']['id'],
];
}
if ($this->guest['sales_retailer']['id'] != 2){ //總經銷
$rows = $this->retailer_relationship_model
->where('relation_type', 'supervisor')
->where('retailer_id', $this->guest['sales_retailer']['retailer_id'])
->where('relation_retailer_id', 2)
->count_rows();
if (!$rows) {
$relationships[] = [
'relation_type' => 'supervisor',
'retailer_id' => $this->guest['sales_retailer']['retailer_id'],
'relation_retailer_id' => 2,
];
}
}
}
if ($this->guest['sales_retailer']['id'] != 2){ //總經銷
$rows = $this->retailer_relationship_model
->where('relation_type', 'supervisor')
->where('retailer_id', $retailer_id)
->where('relation_retailer_id', 2)
->count_rows();
if (!$rows) {
$relationships[] = [
'relation_type' => 'supervisor',
'retailer_id' => $retailer_id,
'relation_retailer_id' => 2,
];
}
}
foreach ($relationships as $relationship) {
$this->retailer_relationship_model->insert($relationship);
}
$purchaseSerialNum = $this->purchase_model->getNextPurchaseSerialNum();
$purchase_id = $this->purchase_model->insert([
'retailer_id' => $retailer_id,
'retailer_address' => $this->guest['retailer']['address'],
'shipout_retailer_id' => $this->guest['sales_retailer']['id'],
'shipin_retailer_id' => $retailer_id,
'shipin_address' => $this->guest['retailer']['address'],
'serialNum' => $purchaseSerialNum,
'purchaseNum' => date('Ym') . $purchaseSerialNum,
'subtotal' => $this->guest['purchase']['subtotal'],
'total' => $this->guest['purchase']['total'],
'memo' => $this->guest['purchase']['memo'],
'dealer_id' => $dealer_id,
]);
$isMatchBox = false;
foreach ($this->guest['purchase']['cart'] as $item) {
$this->purchase_item_model->insert([
'purchase_id' => $purchase_id,
'product_id' => $item['id'],
'price' => $item['price'],
'qty' => $item['qty'],
'subtotal' => $item['price'] * $item['qty'],
'discount' => $this->guest['level']['discount'],
'total' => floor($item['price'] * $this->guest['level']['discount'] / 100) * $item['qty'],
]);
if ($item['qty'] % $item['boxAmount'] == 0){
$isMatchBox = true;
}
}
$this->purchase_model->update([
'isMatchBox' => $isMatchBox,
], ['id' => $purchase_id]);
$this->load->model('payment_model');
$this->payment_model->insert([
'pay_type' => 'purchase',
'pay_id' => $purchase_id,
'paid_retailer_id' => $retailer_id,
'received_retailer_id' => $this->guest['sales_retailer']['id'],
'price' => $this->guest['purchase']['total'],
'retailer_id' => $retailer_id,
'dealer_id' => $dealer_id,
'active' => 0,
]);
$this->session->set_userdata(array('msg' => '訂購成功,敬請在匯款後,回填付款通知單'));
$this->session->unset_userdata('guest');
//登入
if ($this->authentic->authenticate($this->guest['retailer']['account'], $password)) {
redirect('/purchase/detail/' . $purchase_id);
} else {
show_error('登入時發生錯誤');
}
}
}
}
$products = [];
foreach ($this->guest['purchase']['cart'] as $item) {
$products[$item['id']] = $item;
}
$data = [
'guest' => $this->guest,
'products' => $products,
'title' => '經銷商基本資料',
'view' => 'guest/info',
];
$this->_preload($data, 'guest');
}
}
?><file_sep>/application/views/consumer/trashed.php
<div class="container">
<h1 class="mb-4"><?= $dealer['company'] ?>取消之消費紀錄</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">刪除人</th>
<th class="text-center">編號</th>
<th class="text-center">日期</th>
<th class="text-center">姓名</th>
<th class="text-center">電話</th>
<th class="text-center">總額</th>
<th class="text-center"></th>
</tr>
<?php
if ($orders) {
$amount = 0;
foreach ($orders as $order) {
$amount += $order['total'];
?>
<tr>
<td class="text-center"><?= $order['dealer']['name'] ?></td>
<td class="text-center"><?= $order['orderNum'] ?></td>
<td class="text-center"><?= $order['created_at'] ?></td>
<td class="text-center">
<?php if (!empty($authority['customer']) && $order['buyer_id']) { ?>
<a href="<?= base_url('/customer/consumer/' . $order['buyer_id']) ?>"><?= $order['contact']['name'] ?></a>
<?php } ?>
</td>
<td class="text-center">
<?php if ($order['buyer_id']) { ?>
<?= $order['contact']['phone'] ?>
<?php } ?>
</td>
<td class="text-right">$<?= number_format($order['total']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['detail'])){ ?>
<a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $order['id']) ?>">
<i class="fas fa-search"></i> 明細
</a>
<?php } ?>
<?php
if (!empty($authority['recover']) && $order['shipout_retailer_id'] == $dealer['retailer_id']) { ?>
<a class="btn btn-warning btn-sm" href="#"
data-href="<?= base_url('/consumer/recover/' . $order['id']) ?>"
data-toggle="modal" data-target="#confirm-recover">復原</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="7" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal" id="confirm-recover" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">復原確認</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>是否確定復原?</p>
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
<a href="" class="btn btn-danger btn-confirm">復原</a>
</div>
</div>
</div>
</div>
<script>
$().ready(function () {
$('#confirm-recover').on('show.bs.modal', function (e) {
$(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
});
});
</script><file_sep>/application/migrations/026_update_customer_level.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_customer_level extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_customer_levels', [
'description' => [
'type' => 'text',
'default' => '',
'after' => 'discount',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_customer_levels', 'description');
}
}<file_sep>/application/migrations/003_add_retailer.php
<?php
//經銷商基本資料
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_retailer extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'capital_retailer_id' => [ //皮瑪斯的單位
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'sales_retailer_id' => [ //本單位的輔銷人,是單位
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'retailer_role_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'retailer_level_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'serialNum' => [
'type' => 'VARCHAR',
'constraint' => 5,
],
'companyNum' => [
'type' => 'VARCHAR',
'constraint' => 7,
'null' => true,
],
'company' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'invoice_title' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'identity' => [
'type' => 'VARCHAR',
'constraint' => 10,
'null' => true,
],
'contact_dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'altPhone' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'address' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'purchaseThreshold' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'hasStock' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'totalStock' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'eta_days' => [
'type' => 'int',
'constraint' => 3,
'unsigned' => TRUE,
'null' => TRUE,
],
'isLocked' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_retailers');
//olive_retailer_relationships
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'relation_type' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => TRUE,
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'relation_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'alter_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'discount' => [
'type' => 'INT',
'constraint' => 3,
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_retailer_relationships');
}
public function down()
{
$this->dbforge->drop_table('olive_retailers');
$this->dbforge->drop_table('olive_retailer_relationships');
}
}<file_sep>/application/migrations/056_create_product_pao.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Create_product_pao extends CI_Migration {
public function up()
{
$this->dbforge->add_column('product', [
'pao_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
]);
}
public function down()
{
$this->dbforge->drop_column('product', 'pao_id');
}
}<file_sep>/application/models/Shipment_revise_model.php
<?php
class Shipment_revise_model extends MY_Model
{
public $table = 'olive_shipment_revises';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['shipment'] = array('foreign_model' => 'Shipment_model', 'foreign_table' => 'olive_shipments', 'foreign_key' => 'id', 'local_key' => 'shipment_id');
$this->has_many['items'] = array('Shipment_revise_item_model', 'shipment_revise_id', 'id');
}
}
?>
<file_sep>/application/views/recommend/overview.php
<div class="container">
<h1 class="mb-4">行銷作業區</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">編號</th>
<th class="text-left w-25">來賓推薦函</th>
<th class="text-left w-25">來賓推薦照片</th>
</tr>
<?php
if ($recommends) {
foreach ($recommends as $recommend) {
?>
<tr>
<td class="text-center">#<?= $recommend['id'] ?></td>
<td class="text-left">
<?php if ($recommend['picture1']){ ?>
<a href="<?=$recommend['picture1']?>" target="_blank">
<img class="img-fluid" src="<?=$recommend['picture1']?>" />
</a>
<?php } ?>
</td>
<td class="text-left">
<?php if ($recommend['picture2']){ ?>
<a href="<?=$recommend['picture2']?>" target="_blank">
<img class="img-fluid" src="<?=$recommend['picture2']?>" />
</a>
<?php } ?>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="4" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/migrations/051_update_promote_gift_choose.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_promote_gift_choose extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_promote_methods', [
'options' => [
'type' => 'TEXT',
'null' => TRUE,
'after' => 'limit',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_promote_methods', 'options');
}
}<file_sep>/application/views/layout/guest.php
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="designer" content="cystudio, <EMAIL>" />
<title><?= $title ?></title>
<script src="<?= base_url('/js/jquery-3.2.1.slim.min.js')?>"></script>
<script src="<?= base_url('/js/popper.min.js')?>"></script>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','GTM-M5LQ7CP');</script>
<script src="<?= base_url('/js/bootstrap.min.js')?>"></script>
<link href="<?= base_url('css/bootstrap.min.css') ?>" rel="stylesheet" type="text/css">
<link href="<?= base_url('css/styles.css') ?>" rel="stylesheet" type="text/css">
</head>
<body>
<nav class="navbar navbar-light bg-light mb-4">
<a class="navbar-brand" href="<?=base_url('/guest/cart')?>">
<img class="mr-2" height="40" src="<?=base_url('/images/logo.png')?>" />
一顆橄欖貨物管理系統
</a>
</nav>
<?php if (!empty($msg)){ ?>
<div class="container">
<div class="alert alert-info alert-dismissible">
<?=$msg?>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
<?php } ?>
<?php
if (isset($data)) {
$this->load->view($view, $data);
} else {
$this->load->view($view);
}
?>
</body>
</html>
<file_sep>/application/models/Old_customer_model.php
<?php
class Old_customer_model extends MY_Model
{
public $table = 'olive_old_customers';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'old_customer_id', 'local_key' => 'id');
}
}
?>
<file_sep>/application/migrations/054_update_retailer_level_guarantee.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_level_guarantee extends CI_Migration {
public function up()
{
$this->dbforge->add_column('olive_retailer_levels', [
'guarantee' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
'after' => 'monthThreshold',
],
'remark' => [
'type' => 'TEXT',
'null' => TRUE,
'after' => 'sales_commission_type',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_retailer_levels', 'guarantee');
$this->dbforge->drop_column('olive_retailer_levels', 'remark');
}
}<file_sep>/application/models/Promote_model.php
<?php
class Promote_model extends MY_Model
{
public $table = 'olive_promotes';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['methods'] = array('Promote_method_model', 'promote_id', 'id');
}
public function getActivePromotes($retailer_id, $customer = [])
{
$_promotes = $this
->with_methods()
->where('end_at', '>=', date('Y-m-d'))
->where('start_at', '<=', date('Y-m-d'))
->group_start()
->where('exclude_retailers IS NULL', null, null, false, false, true)
->where('NOT FIND_IN_SET("' . $retailer_id . '", exclude_retailers)', null, null, true, false, true)
->group_end()
->order_by('start_at', 'desc')
->get_all();
$promotes = [];
if ($_promotes) {
$customer_created_date = $customer ? date('Y-m-d', strtotime($customer['created_at'])) : null;
$this->load->model('promote_use_model');
$this->load->model('promote_item_model');
$this->load->model('promote_item_relative_model');
foreach ($_promotes as $promote) {
if (!empty($promote['methods'])){
if ($promote['customer_limit'] && $customer){
$total_use = $this->promote_use_model->getUseTime($promote['id'], $customer['id']);
if ($promote['customer_limit'] <= $total_use){
continue;
}
}
if ($promote['customer_type']){
switch ($promote['customer_type']){
case 1: // 特定時間加入之新會員
if (!$customer || !empty($customer['old_customer_id']) || ($promote['customer_start_at'] > $customer_created_date || $promote['customer_end_at'] < $customer_created_date)){
continue 2;
}
break;
case 2: // 特定時間之舊有會員已轉新會員
if (!$customer || empty($customer['old_customer_id']) || ($promote['customer_start_at'] > $customer_created_date || $promote['customer_end_at'] < $customer_created_date)){
continue 2;
}
break;
}
}
$only_gift = true;
foreach ($promote['methods'] as $key => $method){
if ($method['promote_type_id'] != 3){
$only_gift = false;
}
$items = [];
$_product_items = $this->promote_item_model
->with_product(['with' => ['relation' => 'pao']])
->where('promote_method_id', $method['id'])
->where('product_type', 'product')
->get_all();
if ($_product_items){
foreach ($_product_items as $pg){
$items[] = [
'type' => 'product',
'id' => $pg['product_id'],
'name' => $pg['product']['pdName']. $pg['product']['intro2'],
'pao_month' => isset($pg['product']['pao']) ? $pg['product']['pao']['pao_month'] : '',
];
}
}
$_combo_items = $this->promote_item_model
->with_combo()
->where('promote_method_id', $method['id'])
->where('product_type', 'combo')
->get_all();
if ($_combo_items){
foreach ($_combo_items as $cg){
$items[] = [
'type' => 'combo',
'id' => $cg['product_id'],
'name' => $cg['combo']['name'],
'pao_month' => '',
];
}
}
$relatives = [];
$_product_relatives = $this->promote_item_relative_model
->with_product()
->where('promote_method_id', $method['id'])
->where('product_type', 'product')
->get_all();
if ($_product_relatives){
foreach ($_product_relatives as $pg){
$relatives[] = [
'type' => 'product',
'id' => $pg['product_id'],
'name' => $pg['product']['pdName']. $pg['product']['intro2'],
];
}
}
$_combo_items = $this->promote_item_relative_model
->with_combo()
->where('promote_method_id', $method['id'])
->where('product_type', 'combo')
->get_all();
if ($_combo_items){
foreach ($_combo_items as $cg){
$relatives[] = [
'type' => 'combo',
'id' => $cg['product_id'],
'name' => $cg['combo']['name'],
];
}
}
if ($promote['methods'][$key]['options']){
$promote['methods'][$key]['options'] = unserialize($promote['methods'][$key]['options']);
}
$promote['methods'][$key]['items'] = $items;
$promote['methods'][$key]['relatives'] = $relatives;
}
$promote['only_gift'] = $only_gift;
$promotes[$promote['id']] = $promote;
}
}
}
return $promotes;
}
}
?>
<file_sep>/application/views/supervisor/detail.php
<div class="container">
<h1 class="mb-4 text-center">進貨單詳細資料</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>進貨單編號</th>
<td><?= $purchase['purchaseNum'] ?></td>
<th>訂貨日期</th>
<td><?= $purchase['created_at'] ?></td>
</tr>
<tr>
<th>出貨單位</th>
<td><?= $purchase['shipout_retailer']['company'] ?></td>
<th>出貨單位回覆</th>
<td><?= $purchase['confirm_label'] ?></td>
</tr>
<tr>
<th>出貨決定</th>
<td><?= $purchase['shipped_label'] ?></td>
<th>進貨日期</th>
<td><?= $purchase['shipped_at'] ?></td>
</tr>
<tr>
<th>進貨單位付款</th>
<td><?= $purchase['paid_label'] ?></td>
<th>進貨付款日期</th>
<td><?= $purchase['paid_at'] ?></td>
</tr>
<tr>
<th>進貨單位</th>
<td><?= $purchase['retailer']['invoice_title'] ?></td>
<th>進貨單位地址</th>
<td><?= $purchase['retailer_address'] ?></td>
</tr>
<tr>
<th>收貨對象</th>
<td><?= $purchase['shipin_retailer']['invoice_title'] ?></td>
<th>收貨地址</th>
<td>
<?php
echo $purchase['shipin_address'];
if (!$purchase['isMatchBox']){
echo '<div class="text-danger">取貨方式限定親自至輔銷單位取貨</div>';
}
?>
</td>
</tr>
<?php if ($purchase['isInvoice']) { ?>
<tr>
<th>發票對象</th>
<td colspan="3"><?= $purchase['invoice_retailer'] ?></td>
</tr>
<tr>
<th>發票寄送對象</th>
<td><?= $purchase['invoice_send_retailer'] ?></td>
<th>發票寄送地址</th>
<td><?= $purchase['invoice_send_address'] ?></td>
</tr>
<?php } ?>
<tr>
<th>進貨方之備註</th>
<td><?= nl2br($purchase['memo']) ?></td>
<th>出貨方之備註</th>
<td><?= !empty($shipment['memo']) ? nl2br($shipment['memo']) : '' ?></td>
</tr>
</table>
<?php if (!empty($purchase['order_transfer'])) { ?>
<h4 class="mt-5 text-center">A店買B店取貨之紀錄</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">日期</th>
<th class="text-center">取貨人</th>
<th class="text-center">電話</th>
<th class="text-center">售出單位</th>
<th class="text-center">取貨單位</th>
<th class="text-center">新增進貨單</th>
<th class="text-center">開立取貨單</th>
<th class="text-center">是否取貨</th>
</tr>
<tr>
<td class="text-center"><?= date('Y-m-d', strtotime($purchase['order_transfer']['created_at'])) ?></td>
<td class="text-center"><?= empty($purchase['order_transfer']['order']['contact']['name']) ? '' : $purchase['order_transfer']['order']['contact']['name'] ?></td>
<td class="text-center"><?= empty($purchase['order_transfer']['order']['contact']['phone']) ? '' : $purchase['order_transfer']['order']['contact']['phone'] ?></td>
<td class="text-center"><?= $purchase['order_transfer']['retailer']['company'] ?></td>
<td class="text-center"><?= $purchase['order_transfer']['shipout_retailer']['company'] ?></td>
<td class="text-center"><?= yesno($purchase['order_transfer']['purchase_id']) ?></td>
<td class="text-center"><?= yesno($purchase['order_transfer']['isRecorded']) ?></td>
<td class="text-center"><?= yesno($purchase['order_transfer']['isDeliveried']) ?></td>
</tr>
</table>
<?php } ?>
<?php
if ($purchase['items']) {
?>
<h4 class="mt-5 text-center">進貨單詳細商品</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價</th>
<th>折扣</th>
<th>訂購數量</th>
<?php if ($purchase['isShipped']){ ?>
<th>銷貨數量</th>
<?php } ?>
<th>金額小計</th>
</tr>
<?php
if ($purchase['isShipped']){
$colspan = 7;
} else {
$colspan = 6;
}
$i = 1;
foreach ($purchase['items'] as $item) {
?>
<tr<?= ($item['product']['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td><?= $item['product']['p_num'] ?></td>
<td><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td class="text-right">$<?= number_format($item['price']) ?></td>
<td class="text-right"><?= $item['discount'] . '%' ?></td>
<td class="text-right"><?= number_format($item['qty']) ?></td>
<?php if ($purchase['isShipped']){ ?>
<td class="text-right"><?= (!empty($item['shipping_qty'])) ? number_format($item['shipping_qty']) : '' ?></td>
<?php } ?>
<td class="text-right">$<?= number_format($item['total']) ?></td>
</tr>
<?php
$i++;
}
?>
<tr>
<td colspan="<?=$colspan?>" class="text-right font-weight-bold">小計</td>
<td class="text-right font-weight-bold">$<?= number_format($purchase['total']) ?></td>
</tr>
<?php if ($total_allowance_payment > 0) { ?>
<tr>
<td colspan="<?=$colspan?>" class="text-right font-weight-bold">銷貨折讓</td>
<td class="text-right font-weight-bold">- $<?= number_format($total_allowance_payment) ?></td>
</tr>
<tr>
<td colspan="<?=$colspan?>" class="text-right font-weight-bold">總計</td>
<td class="text-right font-weight-bold">$<?= number_format($purchase['total'] - $total_allowance_payment) ?></td>
</tr>
<?php } ?>
</table>
<?php
}
?>
<?php
if ($allowance_payments) {
?>
<h4 class="mt-5 text-center">銷貨折讓紀錄</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>日期</th>
<th>付款單位</th>
<th>收款單位</th>
<th>付款方式</th>
<th>總額</th>
<th>是否付款</th>
<th>付款確認</th>
</tr>
<?php
if ($allowance_payments) {
foreach ($allowance_payments as $ap) {
?>
<tr>
<td><?= $ap['created_at'] ?></td>
<td><?= $ap['paid_retailer']['company'] ?></td>
<td><?= $ap['received_retailer']['company'] ?></td>
<td><?= paymentType($ap['type_id']) ?></td>
<td class="text-right">$<?= number_format($ap['price']) ?></td>
<td class="text-center"><?= yesno($ap['active']) ?></td>
<td class="text-center"><?= $ap['payment_confirm_label'] ?></td>
</tr>
<?php
}
}
?>
</table>
<?php
}
?>
<?php if ($shipments) { ?>
<h4 class="mt-5 text-center">銷貨紀錄</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<thead>
<tr>
<th colspan="2">銷貨日期</th>
<th>寄出單位</th>
<th>取貨單位</th>
<th>是否確認</th>
<th>運費</th>
<th>備註</th>
<td></td>
</tr>
</thead>
<tbody>
<?php
foreach ($shipments as $shipment) {
?>
<tr>
<?php
if (!empty($shipment['isReturn'])) {
?>
<td>銷貨退回</td>
<td><?= $shipment['created_at'] ?></td>
<?php
} elseif (!empty($shipment['isRevised'])) {
?>
<td>已銷貨異動</td>
<td><?= $shipment['created_at'] ?></td>
<?php
} else {
?>
<td colspan="2"><?= $shipment['created_at'] ?></td>
<?php
}
?>
<td><?= $shipment['shipout_retailer']['company'] ?></td>
<td><?= $shipment['shipin_retailer']['company'] ?></td>
<td class="text-center"><?= yesno($shipment['isConfirmed']) ?></td>
<td class="text-right">$<?= empty($shipment['expense']) ? 0 : number_format($shipment['expense']['price']) ?></td>
<td><?= nl2br($shipment['memo']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<button class="btn btn-info" type="button" data-toggle="collapse" data-target="#shipmentItem_<?=$shipment['id']?>" aria-expanded="true">
詳細貨品
</button>
</div>
</td>
</tr>
<tr id="shipmentItem_<?=$shipment['id']?>" class="collapse table-secondary">
<td colspan="8">
<?php if (!empty($shipment['expirations'])) { ?>
<h5>詳細貨品</h5>
<table class="table table-bordered">
<thead>
<tr>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>到期日</th>
<th>收貨數量</th>
</tr>
</thead>
<tbody>
<?php
foreach ($shipment['expirations'] as $item) {
?>
<tr>
<td><?= $item['product']['p_num'] ?></td>
<td><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td><?= $item['expired_at'] ? $item['expired_at'] : '無標示'?></td>
<td class="text-right"><?= number_format($item['qty']) ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php } ?>
<?php if (!empty($shipment['revise']) && $shipment['revise']['isConfirmed']){ ?>
<h5>異動後貨品</h5>
<table class="table table-bordered">
<thead>
<tr class="table-warning">
<th>貨品編號</th>
<th>貨品名稱</th>
<th>到期日</th>
<th>收貨數量</th>
<th>備註</th>
<th>照片</th>
</tr>
</thead>
<tbody>
<?php
if ($shipment['revise']['items']) {
foreach ($shipment['revise']['items'] as $ri) {
?>
<tr class="table-warning">
<td><?= $ri['product']['p_num'] ?></td>
<td><?=$ri['product']['pdName'] . $ri['product']['intro2']?></td>
<td><?=$ri['expired_at'] ? $ri['expired_at'] : '無標示'?></td>
<td class="text-right"><?= number_format($ri['qty']) ?></td>
<td><?=nl2br($ri['memo'])?></td>
<td class="text-center">
<?php if (!is_null($ri['memo_file'])){ ?>
<a href="<?=$ri['memo_file']?>" target="_blank" class="btn btn-info">附件</a>
<?php } ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php } ?>
</td>
</tr>
<?php if (!empty($shipment['revise']) && !$shipment['revise']['isConfirmed']){ ?>
<tr class="table-warning">
<td colspan="8">
<h5>銷貨異動</h5>
<p>確認狀態: <?=yesno($shipment['revise']['isConfirmed'])?></p>
<table class="table table-bordered">
<thead>
<tr class="table-warning">
<th>貨品名稱</th>
<th>到期日</th>
<th>收貨數量</th>
<th>備註</th>
<th>照片</th>
</tr>
</thead>
<tbody>
<?php
if ($shipment['revise']['items']) {
foreach ($shipment['revise']['items'] as $ri) {
?>
<tr class="table-warning">
<td><?=$ri['product']['pdName'] . $ri['product']['intro2']?></td>
<td><?=$ri['expired_at'] ? $ri['expired_at'] : '無標示'?></td>
<td class="text-right"><?= number_format($ri['qty']) ?></td>
<td><?=nl2br($ri['memo'])?></td>
<td class="text-center">
<?php if (!is_null($ri['memo_file'])){ ?>
<a href="<?=$ri['memo_file']?>" target="_blank" class="btn btn-info">附件</a>
<?php } ?>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</td>
</tr>
<?php } ?>
<?php } ?>
</tbody>
</table>
<?php } ?>
</div><file_sep>/application/views/customer/consumer.php
<div class="container">
<h1 class="mb-4">該消費者歷史消費記錄
<div class="float-right">
<?php if (!empty($authority['edit'])){ ?>
<a href="<?= base_url('/customer/edit/' . $customer['id']) ?>" class="btn btn-info"><i class="fas fa-user"></i> 編輯消費者</a>
<?php } ?>
<?php if (!empty($authority['consumer_add'])){ ?>
<a href="<?=base_url('/consumer/add/' . $customer['id']) ?>" class="btn btn-success"><i class="far fa-plus-square"></i> 訂購商品</a>
<?php } ?>
</div>
</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">編號
<div class="float-right">
<a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=1')?>">
<i class="fa fa-sort-amount-down"></i>
</a>
<a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=2')?>">
<i class="fa fa-sort-amount-up"></i>
</a>
</div>
</th>
<th class="text-center">日期
<div class="float-right">
<a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=3')?>">
<i class="fa fa-sort-amount-down"></i>
</a>
<a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=4')?>">
<i class="fa fa-sort-amount-up"></i>
</a>
</div>
</th>
<th class="text-center">總額
<div class="float-right">
<a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=5')?>">
<i class="fa fa-sort-amount-down"></i>
</a>
<a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=6')?>">
<i class="fa fa-sort-amount-up"></i>
</a>
</div>
</th>
<th class="text-center">營業單位
<div class="float-right">
<a title="編號降序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=7')?>">
<i class="fa fa-sort-amount-down"></i>
</a>
<a title="編號升序" href="<?=base_url('/customer/consumer/' . $customer['id'] . '?sortby=8')?>">
<i class="fa fa-sort-amount-up"></i>
</a>
</div>
</th>
<th class="text-center"></th>
</tr>
<?php
if ($orders) {
$amount = 0;
foreach ($orders as $order) {
$amount += $order['total'];
?>
<tr>
<td class="text-center"><?= $order['orderNum'] ?></td>
<td class="text-center"><?= $order['created_at'] ?></td>
<td class="text-right">$<?= number_format($order['total']) ?></td>
<td class="text-center"><?= $order['retailer']['company'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['consumer_detail'])){ ?>
<a class="btn btn-info btn-sm" href="<?= base_url('/consumer/detail/' . $order['id']) ?>">
<i class="fas fa-search"></i> 詳細
</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
?>
<tr>
<th colspan="2" class="text-right">累計消費金額</th>
<td class="text-right">
$<?= number_format($amount) ?>
</td>
<td></td>
<td></td>
</tr>
<?php
} else {
?>
<tr>
<td colspan="5" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/controllers/Capital_black_vip.php
<?php
class Capital_black_vip extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
$this->load->model('customer_level_history_model');
$this->load->model('customer_model');
$this->load->library('customer_lib');
$this->session->set_userdata('return_page', base_url('/customer/overview'));
}
public function overview()
{
$total_customers_count = $this->customer_level_history_model
->where('new_customer_level_id', 3)
->where('isConfirmed', 0)
->count_rows();
$customers = $this->customer_level_history_model
->with_customer()
->where('new_customer_level_id', 3)
->where('isConfirmed', 0)
->order_by('id', 'desc')
->paginate(20, $total_customers_count);
$this->load->helper('data_format');
//權限設定
$authority = array();
if ($this->authentic->authority('capital_black_vip', 'confirm')){
$authority['confirm'] = true;
}
if ($this->authentic->authority('capital_black_vip', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'customers' => $customers,
'pagination' => $this->customer_level_history_model->all_pages,
'authority' => $authority,
'title' => '曜石黑卡審核遴選',
'view' => 'capital/black_vip/overview',
];
$this->_preload($data);
}
public function confirm($customer_level_history_id)
{
$customer_level_history = $this->customer_level_history_model
->where('isConfirmed', 0)
->get($customer_level_history_id);
if (!$customer_level_history_id || !$customer_level_history) {
show_error('查無曜石黑卡審核遴選資料');
}
$this->load->model('confirm_model');
$this->confirm_model->insert([
'confirm_type' => 'customer_level_history',
'confirm_id' => $customer_level_history_id,
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => 1,
'dealer_id' => $this->dealer['id'],
]);
$this->customer_level_history_model->update(['isConfirmed' => 1], ['id' => $customer_level_history_id]);
$this->customer_model->update([
'customer_level_id' => 3,
], ['id' => $customer_level_history['customer_id']]);
redirect(base_url('/capital_black_vip/overview'));
}
public function cancel($customer_level_history_id)
{
$customer_level_history = $this->customer_level_history_model
->where('isConfirmed', 0)
->get($customer_level_history_id);
if (!$customer_level_history_id || !$customer_level_history) {
show_error('查無曜石黑卡審核遴選資料');
}
$this->customer_level_history_model->delete($customer_level_history_id);
redirect(base_url('/capital_black_vip/overview'));
}
}
?><file_sep>/application/models/Stock_counting_model.php
<?php
class Stock_counting_model extends MY_Model
{
public $table = 'olive_stock_countings';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['items'] = array('Stock_counting_item_model', 'stock_counting_id', 'id');
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['dealer'] = array('foreign_model' => 'Dealer_model', 'foreign_table' => 'olive_dealers', 'foreign_key' => 'id', 'local_key' => 'dealer_id');
}
public function getNextSerialNum($counting_reason)
{
$stock_counting = $this
->with_trashed()
->where('DATE_FORMAT(created_at,"%Y-%m-%d") = "' . date('Y-m-d') . '"', null, null, false, false, true)
->where('counting_reason', $counting_reason)
->order_by('serialNum', 'desc')
->get();
if ($stock_counting) {
$num = (int)$stock_counting['serialNum'] + 1;
return str_pad($num, 2, '0', STR_PAD_LEFT);
} else {
return '01';
}
}
}
?>
<file_sep>/application/models/Dealer_model.php
<?php
class Dealer_model extends MY_Model
{
public $table = 'olive_dealers';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['retailer'] = array('foreign_model' => 'Retailer_model', 'foreign_table' => 'olive_retailers', 'foreign_key' => 'id', 'local_key' => 'retailer_id');
$this->has_one['group'] = array('foreign_model' => 'Retailer_group_model', 'foreign_table' => 'olive_retailer_groups', 'foreign_key' => 'id', 'local_key' => 'retailer_group_id');
}
public function getDealerSelect($retailer_id='')
{
if ($retailer_id){
$this->where('retailer_id', $retailer_id);
} else {
$this->with_retailer(['fields' => 'company']);
}
$_dealers = $this
->order_by('retailer_id', 'asc')
->order_by('account', 'asc')
->get_all();
$dealers = [];
if ($_dealers) {
foreach ($_dealers as $dealer) {
if ($retailer_id) {
$dealers[$dealer['id']] = $dealer['name'];
} else {
$dealers[$dealer['id']] = '(' . $dealer['retailer']['company'] . ')' . $dealer['name'];
}
}
}
return $dealers;
}
}
?>
<file_sep>/application/views/capital/product/permission/edit.php
<div class="container">
<h1 class="mb-4">編輯<?=$product['pdName'] . $product['intro2']?>進貨商品</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">可進貨單位</label>
<select id="include_retailers" name="include_retailers[]" class="form-control" multiple>
<?php foreach ($retailers as $retailer_id => $retailer_name) { ?>
<option value="<?= $retailer_id ?>" <?php if (set_value('include_retailers', $permission['retailers']) && in_array($retailer_id, set_value('include_retailers', $permission['retailers']))){ echo 'selected';} ?>><?= $retailer_name ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label class="font-weight-bold">備註</label>
<textarea rows="4" name="remark" class="form-control"><?= set_value('remark', $permission['remark']) ?></textarea>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/capital_product/overview/') ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css"
integrity="<KEY>="anonymous"/>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css"
integrity="<KEY> crossorigin="anonymous"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script>
$().ready(function () {
$('#include_retailers').select2({
theme: "bootstrap",
multiple: true,
placeholder: '選擇可進貨單位'
});
});
</script><file_sep>/application/views/recommend/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">修改暫存作業</h1>
<form method="post" enctype="multipart/form-data">
<?php if ($error) { ?>
<div class="alert alert-danger">
<?= implode('<br>', $error) ?>
</div>
<?php } ?>
<div class="card mb-4">
<div class="card-header">上傳來賓推薦函或行銷同意書(即無內容之來賓推薦函) / (先行作業:將已簽名之推薦函拍照傳入或掃描傳入電腦中之指定資料夾)</div>
<div class="card-body">
<?php if ($recommend['picture1']){ ?>
<div class="w-25 mb-2">
<a href="<?=$recommend['picture1']?>" target="_blank">
<img class="img-fluid" src="<?=$recommend['picture1']?>" />
</a>
</div>
<?php } ?>
<input type="file" class="form-control-file" name="picture1" />
</div>
</div>
<div class="card mb-4">
<div class="card-header">上傳來賓推薦照片 / (先行作業:來賓拍照後將照片傳至電腦)</div>
<div class="card-body">
<?php if ($recommend['picture2']){ ?>
<div class="w-25 mb-2">
<a href="<?=$recommend['picture2']?>" target="_blank">
<img class="img-fluid" src="<?=$recommend['picture2']?>" />
</a>
</div>
<?php } ?>
<input type="file" class="form-control-file" name="picture2" />
</div>
</div>
<div class="form-group d-flex justify-content-end">
<input type="submit" name="temp_add" class="btn btn-success mr-2" value="暫存 / 先做別的"/>
<input type="submit" name="complete_add" class="btn btn-success" value="推薦作業完成"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/controllers/Capital_option.php
<?php
class Capital_option extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('option_model');
$this->session->set_userdata('return_page', base_url('/capital_option/overview'));
}
public function customer()
{
if ($this->input->post()) {
$this->form_validation->set_rules('customer_staff_max_amount', '員工每季消費上限', 'required|integer|greater_than_equal_to[0]');
if ($this->form_validation->run() !== FALSE) {
$this->option_model
->where('name', 'like', 'customer')
->delete();
$this->option_model->insert([
'name' => 'customer_staff_max_amount',
'value' => $this->input->post('customer_staff_max_amount'),
]);
redirect(base_url('/capital_option/customer/'), 'refresh');
}
}
$_options = $this->option_model
->where('name', 'like', 'customer')
->get_all();
$options = [];
if ($_options){
foreach ($_options as $option){
$options[$option['name']] = $option['value'];
}
}
$data = [
'options' => $options,
'title' => '編輯消費者參數',
'view' => 'capital/option/customer',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/supervisor/purchase.php
<div class="container">
<h1 class="mb-4"><?=$retailer['company']?> 經銷商進貨明細</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">進貨單編號</th>
<th class="text-center">訂貨日期</th>
<th class="text-center">進貨日期</th>
<th class="text-center">出貨單位</th>
<th class="text-center">進貨金額</th>
<th class="text-center"></th>
</tr>
<?php
if ($purchases) {
foreach ($purchases as $purchase) {
?>
<tr>
<td class="text-center"><?= $purchase['purchaseNum'] ?></td>
<td class="text-center"><?= $purchase['created_at'] ?></td>
<td class="text-center"><?= $purchase['shipped_at'] ?></td>
<td class="text-center"><?= empty($purchase['shipout_retailer']) ? '' : $purchase['shipout_retailer']['company'] ?></td>
<td class="text-center">$<?= number_format($purchase['subtotal']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['detail'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/supervisor/detail/' . $purchase['id']) ?>">
<i class="fas fa-search"></i> 詳細
</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="6" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
</div><file_sep>/application/migrations/044_add_product_permission.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_product_permission extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'include_retailers' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => TRUE,
],
'remark' => [
'type' => 'TEXT',
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_product_permissions');
}
public function down()
{
$this->dbforge->drop_table('olive_product_permissions');
}
}<file_sep>/application/views/confirm/overview.php
<div class="container">
<h1 class="mb-4">確認紀錄列表</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">日期</th>
<th class="text-center">確認者名稱</th>
<th class="text-center">結果</th>
<th class="text-center">備註</th>
</tr>
<?php
if ($confirms) {
foreach ($confirms as $confirm) {
?>
<tr>
<td class="text-center"><?= $confirm['created_at'] ?></td>
<td class="text-center"><?= $confirm['retailer']['company'] ?></td>
<td class="text-center"><?=confirmStatus($confirm['audit'])?></td>
<td class="text-center"><?=$confirm['memo']?></td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="4" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/models/Purchase_shortage_model.php
<?php
class Purchase_shortage_model extends MY_Model
{
public $table = 'olive_purchase_shortages';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
$this->has_one['item'] = array('foreign_model' => 'Purchase_item_model', 'foreign_table' => 'olive_purchase_items', 'foreign_key' => 'id', 'local_key' => 'purchase_item_id');
$this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
}
public function getTransferShortage($shortage_id, $isTransfer = false)
{
$transfer_purchase_id = '';
if (!$isTransfer) {
$shortage = $this
->with_purchase()
->with_item()
->get($shortage_id);
if ($shortage && $shortage['purchase'] && $shortage['item'] && !is_null($shortage['purchase']['transfer_id'])) {
$transfer_purchase_id = $shortage['purchase']['transfer_id'];
$product_id = $shortage['item']['product_id'];
}
} else {
$shortage = $this
->with_purchase(['with' => ['relation' => 'transfer_from']])
->with_item()
->get($shortage_id);
if ($shortage && $shortage['purchase'] && $shortage['item'] && $shortage['purchase']['transfer_from']) {
$transfer_purchase_id = $shortage['purchase']['transfer_from']['id'];
$product_id = $shortage['item']['product_id'];
}
}
if ($transfer_purchase_id) {
$this->load->model('purchase_item_model');
$transfer_purchase_item = $this->purchase_item_model->getPurchaseItemOfId($transfer_purchase_id, $product_id);
if ($transfer_purchase_item && $transfer_purchase_item['shortage']) {
return $transfer_purchase_item;
}
}
return false;
}
}
?>
<file_sep>/application/views/purchase/edit.php
<div class="container">
<h1 class="mb-4 text-center">編輯進貨單</h1>
<form method="post" id="purchaseForm">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">進貨日期</label>
<input type="date" name="created_at" class="form-control" value="<?= set_value('created_at', date('Y-m-d', strtotime($purchase['created_at']))) ?>" required/>
</div>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價(含稅)</th>
<th>訂購數量</th>
<th>金額小計</th>
<th>折扣</th>
<th>折扣價</th>
</tr>
<?php if ($purchase['items']) {
$i = 1;
foreach ($purchase['items'] as $item) {
?>
<tr<?= ($item['product']['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td><?= $item['product']['p_num'] ?></td>
<td>
<?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?>
</td>
<td>
<input type="number" name="items[<?= $item['product_id'] ?>][price]" data-qty="<?= $item['qty'] ?>" min="0" required class="item_cash form-control text-right" value="<?=$item['price']?>" />
</td>
<td class="text-right"><?= $item['qty'] ?></td>
<td class="item_subtotal text-right">$<?= number_format($item['subtotal']) ?></td>
<td>
<div class="input-group">
<input type="number" name="items[<?= $item['product_id'] ?>][discount]" min="1" max="100" required class="item_discount form-control text-right" value="<?=$item['discount']?>" />
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
</td>
<td>
<input type="number" name="items[<?= $item['product_id'] ?>][total]" min="0" required class="item_total form-control text-right" value="<?=$item['total']?>" />
</td>
</tr>
<?php
$i++;
}
}
?>
<tr>
<td colspan="6"></td>
<td class="text-right font-weight-bold">總計</td>
<td id="total_text" class="text-right font-weight-bold">$<?=number_format($purchase['total'])?></td>
</tr>
</table>
<div class="form-group text-center">
<a href="<?= base_url('/purchase/overview/') ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
<script>
$().ready(function () {
$('#purchaseForm input.item_cash').change(function () {
var price = parseInt($(this).val());
var qty = parseInt($(this).data('qty'));
var item = $(this).parents('tr');
item.find('td.item_subtotal').text(numberWithCommas(price * qty));
var discount = parseInt(item.find('.item_discount').val()) || 100;
var discount_price = Math.floor(price * discount / 100) * qty;
item.find('.item_total').val(discount_price);
calc_total();
});
$('#purchaseForm input.item_discount').change(function () {
var discount = parseInt($(this).val()) || 100;
var item = $(this).parents('tr');
var price = parseInt(item.find('.item_cash').val());
var qty = parseInt(item.find('.item_cash').data('qty'));
var discount_price = Math.floor(price * discount / 100) * qty;
item.find('.item_total').val(discount_price);
calc_total();
});
$('#purchaseForm input.item_total').change(function () {
calc_total();
});
function calc_total() {
var total = 0;
$('#purchaseForm input.item_total').each(function () {
total += parseInt($(this).val());
});
$('#total_text').text('$' + numberWithCommas(total));
}
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$("#purchaseForm").keydown(function(e){
if(e.keyCode == 13) {
e.preventDefault();
return false;
}
});
</script><file_sep>/application/controllers/Capital_privilege.php
<?php
class Capital_privilege extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('privilege_model');
$this->session->set_userdata('return_page', base_url('/capital_privilege/overview'));
}
public function overview()
{
$this->config->load('class_list', true);
$class_list = $this->config->item('class_list');
$privileges = $this->privilege_model
->get_all();
if ($privileges) {
foreach ($privileges as $privilege) {
if (!isset($class_list[$privilege['classname']])) {
$this->privilege_model->delete($privilege['id']);
}
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('capital_privilege', 'apps')){
$authority['apps'] = true;
}
$data = [
'class_list' => $class_list,
'authority' => $authority,
'title' => '權限總覽',
'view' => 'capital/privilege/overview',
];
$this->_preload($data);
}
public function apps($classname)
{
$this->config->load('class_list', true);
$class_list = $this->config->item('class_list');
if (!$classname || empty($class_list[$classname])) {
show_error('頁面名稱錯誤');
}
$privileges = $this->privilege_model
->where('classname', $classname)
->get_all();
if ($privileges) {
foreach ($privileges as $privilege) {
if (!isset($class_list[$classname]['method'][$privilege['methodname']])) {
$this->privilege_model->delete($privilege['id']);
}
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('capital_privilege', 'authority')){
$authority['authority'] = true;
}
$data = [
'classname' => $classname,
'class_list' => $class_list,
'authority' => $authority,
'title' => '頁面權限總覽',
'view' => 'capital/privilege/apps',
];
$this->_preload($data);
}
public function authority($classname, $methodname)
{
$this->config->load('class_list', true);
$class_list = $this->config->item('class_list');
if (!$classname || empty($class_list[$classname])) {
show_error('頁面名稱錯誤');
}
if (empty($class_list[$classname]['method'][$methodname])) {
show_error('動作名稱錯誤');
}
$privilege = $this->privilege_model
->where('classname', $classname)
->where('methodname', $methodname)
->get();
$rules = [];
if ($privilege) {
$rules = unserialize($privilege['rules']);
}
$permission = [
0 => '禁止',
1 => '允許',
];
$this->load->model('retailer_group_model');
$_groups = $this->retailer_group_model
->with_role()
->with_level_type()
->order_by('retailer_role_id')
->order_by('id')
->get_all();
if (!$_groups){
show_error('尚未設定群組');
}
$groups = [];
foreach ($_groups as $group){
if ($rules && isset($rules[$group['id']])){
$group['permission'] = $rules[$group['id']];
} else {
$group['permission'] = 0;
}
$groups[$group['id']] = $group;
}
if ($this->input->post()) {
$this->form_validation->set_rules('rules[]', '權限設定', 'required|integer|in_list[' . implode(',', array_keys($permission)) . ']');
if ($this->form_validation->run() !== FALSE) {
$_rules = (array)$this->input->post('rules');
$new_rules = [];
if ($_rules){
foreach ($_rules as $group_id => $group_val){
if (in_array($group_id, array_keys($groups))){
$new_rules[$group_id] = $group_val;
}
}
}
if ($privilege) {
$this->privilege_model->update([
'rules' => serialize($new_rules),
], ['id' => $privilege['id']]);
} else {
$this->privilege_model->insert([
'classname' => $classname,
'methodname' => $methodname,
'rules' => serialize($new_rules),
]);
}
redirect(base_url('/capital_privilege/apps/' . $classname));
}
}
$data = [
'classname' => $classname,
'methodname' => $methodname,
'class_list' => $class_list,
'groups' => $groups,
'permission' => $permission,
'title' => '動作權限設定',
'view' => 'capital/privilege/authority',
];
$this->_preload($data);
}
}<file_sep>/application/views/welcome.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4 text-center">歡迎 <?= $dealer['company'] ?></h1>
<div class="card">
<div class="card-header">基本資料</div>
<div class="card-body">
<p class="card-text">帳號: <?= $dealer['account'] ?></p>
<p class="card-text">名字: <?= $dealer['name'] ?></p>
<p class="card-text">身份證字號/統一編號: <?= $dealer['identity'] ?></p>
<p class="card-text">性別: <?= $dealer['gender'] ? '男' : '女' ?></p>
<p class="card-text">聯絡電話1: <?= $dealer['phone'] ?></p>
<p class="card-text">聯絡電話2: <?= $dealer['altPhone'] ?></p>
<p class="card-text">送貨地址: <?= $dealer['address'] ?></p>
<?php if (!empty($dealer['sales_retailer'])) { ?>
<p class="card-text">輔銷單位: <?= $dealer['sales_retailer']['company'] ?></p>
<?php } ?>
<?php if (!empty($dealer['sales_dealer'])) { ?>
<p class="card-text">輔銷人: <?= $dealer['sales_dealer']['name'] ?></p>
<?php } ?>
</div>
</div>
</div>
</div>
</div>
<file_sep>/application/models/Purchase_return_model.php
<?php
class Purchase_return_model extends MY_Model
{
public $table = 'olive_purchase_returns';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
$this->has_one['item'] = array('foreign_model' => 'Purchase_item_model', 'foreign_table' => 'olive_purchase_items', 'foreign_key' => 'id', 'local_key' => 'purchase_item_id');
$this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
}
}
?>
<file_sep>/application/views/consumer/edit.php
<div class="container">
<h1 class="mb-4">編輯消費紀錄</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">訂單日期</label>
<input type="date" name="created_at" class="form-control" value="<?= set_value('created_at', date('Y-m-d', strtotime($order['created_at']))) ?>" required/>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/consumer/overview/') ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div><file_sep>/application/models/Pao_model.php
<?php
class Pao_model extends MY_Model
{
public $table = 'olive_paos';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
}
public function getPaoSelect()
{
$_paos = $this->get_all();
$paos = [];
if ($_paos) {
foreach ($_paos as $pao) {
$paos[$pao['id']] = '有效期限' . $pao['expiration_month'] . '月(PAO: ' . $pao['pao_month'] . '月)';
}
}
return $paos;
}
}
?>
<file_sep>/application/controllers/Purchase.php
<?php
class Purchase extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('purchase_model');
$this->load->model('purchase_item_model');
$this->load->model('shipment_model');
$this->load->model('shipment_item_model');
$this->load->library('stock_lib');
$this->load->library('purchase_lib');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/purchase/overview'));
}
public function overview()
{
$shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);
$search = array(
'purchaseNum' => $this->input->get('purchaseNum'),
'created_start' => $this->input->get('created_start'),
'created_end' => $this->input->get('created_end'),
'isConfirmed' => $this->input->get('isConfirmed'),
'isPaid' => $this->input->get('isPaid'),
'isShipped' => $this->input->get('isShipped'),
'isReceived' => $this->input->get('isReceived'),
'shipout_retailer_id' => (int)$this->input->get('shipout_retailer_id'),
);
if ($search['purchaseNum'] != ''){
$this->purchase_model->where('purchaseNum', $search['purchaseNum']);
}
if ($search['created_start'] != ''){
$this->purchase_model->where('created_at', '>=', $search['created_start']);
}
if ($search['created_end'] != ''){
$this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
}
if ($search['isConfirmed'] != ''){
if ($search['isConfirmed'] == '-1'){
$this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
} else {
$this->purchase_model->where('isConfirmed', $search['isConfirmed']);
}
}
if ($search['isPaid'] != ''){
$this->purchase_model->where('isPaid', $search['isPaid']);
}
if ($search['isShipped'] != ''){
$this->purchase_model->where('isShipped', $search['isShipped']);
}
if ($search['isReceived'] != ''){
if ($search['isReceived'] == 'isCorrect') {
$this->purchase_model->where('isShipConfirmed', 1);
} elseif ($search['isReceived'] == 'isRevised'){
$this->purchase_model->where('isRevised', 1);
} elseif ($search['isReceived'] == 'isReturn'){
$this->purchase_model->where('isReturn', 1);
} elseif ($search['isReceived'] == 'isAllowance'){
$this->purchase_model->where('isAllowance', 1);
}
}
if ($search['shipout_retailer_id'] != ''){
$this->purchase_model->where('shipout_retailer_id', $search['shipout_retailer_id']);
}
$total_purchases_count = $this->purchase_model
->with_trashed()
->where('retailer_id', $this->dealer['retailer_id'])
->count_rows();
if ($search['purchaseNum'] != ''){
$this->purchase_model->where('purchaseNum', $search['purchaseNum']);
}
if ($search['created_start'] != ''){
$this->purchase_model->where('created_at', '>=', $search['created_start']);
}
if ($search['created_end'] != ''){
$this->purchase_model->where('created_at', '<=', date('Y-m-d', strtotime($search['created_end'] . " +1 days")));
}
if ($search['isConfirmed'] != ''){
if ($search['isConfirmed'] == '-1'){
$this->purchase_model->where('isConfirmed IS NULL', null, null, false, false, true);
} else {
$this->purchase_model->where('isConfirmed', $search['isConfirmed']);
}
}
if ($search['isPaid'] != ''){
$this->purchase_model->where('isPaid', $search['isPaid']);
}
if ($search['isShipped'] != ''){
$this->purchase_model->where('isShipped', $search['isShipped']);
}
if ($search['isReceived'] != ''){
if ($search['isReceived'] == 'isCorrect') {
$this->purchase_model->where('isShipConfirmed', 1);
} elseif ($search['isReceived'] == 'isRevised'){
$this->purchase_model->where('isRevised', 1);
} elseif ($search['isReceived'] == 'isReturn'){
$this->purchase_model->where('isReturn', 1);
} elseif ($search['isReceived'] == 'isAllowance'){
$this->purchase_model->where('isAllowance', 1);
}
}
if ($search['shipout_retailer_id'] != ''){
$this->purchase_model->where('shipout_retailer_id', $search['shipout_retailer_id']);
}
$purchases = $this->purchase_model
->with_trashed()
->with_transfer_from()
->with_retailer(['fields' => 'company'])
->with_shipin_retailer('fields:company')
->with_shipout_retailer('fields:company')
->with_items()
->with_order_transfer()
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_shipments(['non_exclusive_where' => "`ship_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='shipment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->where('retailer_id', $this->dealer['retailer_id'])
->order_by($this->purchase_model->get_table_name() . '.id', 'desc')
->paginate(20, $total_purchases_count);
if ($purchases) {
foreach ($purchases as $key => $purchase) {
$purchase_lib = new purchase_lib($purchase);
$purchases[$key]['paid_label'] = $purchase_lib->generatePaidLabel();
$purchases[$key]['confirm_label'] = $purchase_lib->generateConfirmLabel();
$purchases[$key]['shipped_label'] = $purchase_lib->generateShippedLabel();
}
}
//權限設定
$authority = array();
if (!$this->dealer['disabled'] && $this->authentic->authority('purchase', 'add')){
$authority['add'] = true;
}
if (!$this->dealer['disabled'] && $this->authentic->authority('purchase', 'add2')){
$authority['add2'] = true;
}
if ($this->authentic->authority('purchase', 'detail')){
$authority['detail'] = true;
}
if ($this->authentic->authority('purchase', 'detail2')){
$authority['detail2'] = true;
}
if ($this->authentic->authority('purchase', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('purchase', 'cancel')){
$authority['cancel'] = true;
}
if ($this->authentic->authority('payment', 'add')){
$authority['payment_add'] = true;
}
if ($this->authentic->authority('shipment', 'confirm')){
$authority['shipment_confirm'] = true;
}
if ($this->authentic->authority('shipment', 'return_add')){
$authority['return_add'] = true;
}
if ($this->authentic->authority('shipment', 'allowance_add')){
$authority['allowance_add'] = true;
}
$data = [
'shipout_retailers' => $shipout_retailers,
'search' => $search,
'purchases' => $purchases,
'pagination' => $this->purchase_model->all_pages,
'authority' => $authority,
'title' => '進貨單列表',
'view' => 'purchase/overview',
];
$this->_preload($data);
}
public function detail($purchase_id, $show_price = true)
{
$purchase = $this->purchase_model
->with_trashed()
->with_transfer_from()
->with_retailer('fields:company,invoice_title')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_order_transfer(['with' =>
[
['relation' => 'order', 'with' => ['contact']],
['relation' => 'retailer'],
['relation' => 'shipout_retailer'],
]
])
->with_items(['with' =>
[
'relation' => 'product',
'with' => ['relation' => 'product_kind', 'fields' => 'ctName']
]
])
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->where('retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無進貨單資料');
}
$purchase_lib = new purchase_lib($purchase);
$purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
$purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
$purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
$shipments = [];
$allowance_payments = [];
$total_allowance_payment = 0;
if ($purchase['isShipped']) {
$real_shipin_retailer = $purchase['shipin_retailer'];
$real_shipout_retailer = $purchase['shipout_retailer'];
if (!is_null($purchase['transfer_id'])){
$transfer_to_purchase = $this->purchase_model
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->get($purchase['transfer_id']);
if ($transfer_to_purchase){
$real_shipout_retailer = $transfer_to_purchase['shipout_retailer'];
}
}
$this->load->model('payment_model');
//銷貨折讓
$payments = $this->payment_model
->with_paid_retailer('fields:company,invoice_title')
->with_received_retailer('fields:company,invoice_title')
->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
->where('pay_type', 'shipment_allowance')
->where('pay_id', $purchase_id)
->get_all();
if ($payments) {
foreach ($payments as $payment){
$payment['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
$allowance_payments[] = $payment;
if ($payment['active'] && $payment['isConfirmed']) {
$total_allowance_payment += $payment['price'];
}
}
}
$_shipments = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->order_by('id', 'asc')
->get_all();
if ($_shipments){
foreach ($_shipments as $shipment){
if ($shipment['shipin_retailer_id'] != $purchase['retailer_id']){
$shipment['isReturn'] = true;
$shipment['shipout_retailer'] = $real_shipin_retailer;
$shipment['shipin_retailer'] = $real_shipout_retailer;
} else {
$shipment['shipout_retailer'] = $real_shipout_retailer;
$shipment['shipin_retailer'] = $real_shipin_retailer;
}
$shipments[] = $shipment;
if (is_null($shipment['shipment_id'])) {
$revised = $this->shipment_model
->with_expirations(['with' => ['relation' => 'product']])
->with_revise(['with' => ['relation' => 'items', 'with' => ['relation' => 'product']]])
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('shipment_id', $shipment['id'])
->where('isConfirmed', 0)
->order_by('id', 'asc')
->get_all();
if ($revised) {
$revised['shipout_retailer'] = $real_shipout_retailer;
$revised['shipin_retailer'] = $real_shipin_retailer;
$shipments = array_merge($shipments, $revised);
}
}
}
if ($shipments){
foreach ( array_reverse($shipments) as $shipment ) {
if ($shipment['isConfirmed'] || !empty($shipment['isReturn'])) {
foreach ($shipment['expirations'] as $sitem) {
foreach ($purchase['items'] as $pkey => $pitem) {
if ($sitem['product_id'] == $pitem['product_id']) {
if (!isset($purchase['items'][$pkey]['shipping_qty'])){
$purchase['items'][$pkey]['shipping_qty'] = 0;
}
if (!empty($shipment['isReturn'])){
$purchase['items'][$pkey]['shipping_qty'] -= $sitem['qty'];
} else {
$purchase['items'][$pkey]['shipping_qty'] += $sitem['qty'];
}
}
}
}
if (empty($shipment['isReturn'])) {
break;
}
}
}
}
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('shipment', 'revise_edit')){
$authority['revise_edit'] = true;
}
if ($this->authentic->authority('payment', 'confirm')){
$authority['payment_confirm'] = true;
}
$data = [
'purchase' => $purchase,
'shipments' => $shipments,
'allowance_payments' => $allowance_payments,
'total_allowance_payment' => $total_allowance_payment,
'show_price' => $show_price,
'authority' => $authority,
'title' => '進貨單詳細資料',
'view' => 'purchase/detail',
];
$this->_preload($data);
}
//不能看到價格
public function detail2($purchase_id)
{
$this->detail($purchase_id, false);
}
//不能看到價格
public function add2($shipout_retailer_id = '', $shipin_retailer_id = '')
{
$this->add($shipout_retailer_id, $shipin_retailer_id, false);
}
public function add($shipout_retailer_id = '', $shipin_retailer_id = '', $show_price = true)
{
if ($this->dealer['disabled']){
show_error('因進貨金額不到最低門檻,故已被取消經銷商資格且無法進貨,後續事宜請聯繫您的輔銷人!');
}
$this->load->model('retailer_model');
$this->load->model('retailer_relationship_model');
$this->load->model('product_relationship_model');
$discount = 100;
$products = [];
$shipin_retailers = [];
$invoice_retailers = [];
$invoice_send_retailers = [];
$shipout_retailers = $this->purchase_lib->getShipOutList($this->dealer['retailer_id']);
if (count($shipout_retailers) == 1) {
$shipout_retailer_id = current(array_keys($shipout_retailers));
}
if ($shipout_retailer_id && isset($shipout_retailers[$shipout_retailer_id])) {
$shipout_retailer = $shipout_retailers[$shipout_retailer_id];
$discount = $shipout_retailer['discount'];
$shipin_retailers = $this->purchase_lib->getShipInList($this->dealer['retailer_id'], $shipout_retailer_id);
if (count($shipin_retailers) == 1) {
$shipin_retailer_id = current(array_keys($shipin_retailers));
}
if ($shipin_retailer_id) {
$shipin_retailer = $shipin_retailers[$shipin_retailer_id];
$invoice_retailers = $this->purchase_lib->getInvoiceList($this->dealer['retailer_id'], $shipout_retailer_id);
$invoice_send_retailers = $this->purchase_lib->getInvoiceSendList($this->dealer['retailer_id']);
if ($shipin_retailer_id != $this->dealer['retailer_id']){
//取得產品折扣值
$relationship_products = $this->product_relationship_model->getRelationshipProducts($shipin_retailer_id, $this->dealer['retailer_id']);
} else {
//取得產品折扣值
$relationship_products = $this->product_relationship_model->getRelationshipProducts($this->dealer['retailer_id'], $shipout_retailer_id);
}
$this->load->model('product_model');
$this->load->model('product_permission_model');
$this->load->model('stock_model');
$products = $this->product_permission_model->getPermissionProducts($this->dealer['retailer_id']);
$stock_table = $this->stock_model->get_table_name();
foreach ($products as $product_id => $product) {
$products[$product_id]['discount'] = empty($relationship_products[$product_id]) ? null : $relationship_products[$product_id];
}
if ($shipout_retailer['hasStock'] || $shipin_retailer['hasStock']) {
$enableStep = (!empty($this->dealer['isAllowBulk'])) ? false : true;
foreach ($products as $product_id => $product) {
$products[$product_id]['step'] = $enableStep ? $product['boxAmount'] : 1;
if ($shipin_retailer['hasStock']) {
$stock = $this->stock_model
->fields('SUM(' . $stock_table . '.stock) as active_total')
->where('product_id', $product_id)
->where('retailer_id', $shipin_retailer_id)
->where('stock', '>', 0)
->group_start()
->where('expired_at', '>=', date('Y-m-d'), true)
->where('expired_at IS NULL', null, null, true, false, true)
->group_end()
->order_by('ISNULL(expired_at)', 'asc')
->order_by('expired_at', 'asc')
->get();
$products[$product_id]['stock']['shipin'] = $stock['active_total'];
}
if ($shipout_retailer['hasStock']) {
$stock = $this->stock_model
->fields('SUM(' . $stock_table . '.stock) as active_total')
->where('product_id', $product_id)
->where('retailer_id', $shipout_retailer_id)
->where('stock', '>', 0)
->group_start()
->where('expired_at', '>=', date('Y-m-d'), true)
->where('expired_at IS NULL', null, null, true, false, true)
->group_end()
->order_by('ISNULL(expired_at)', 'asc')
->order_by('expired_at', 'asc')
->get();
if ($stock && $product['boxAmount'] <= $stock['active_total']) {
$products[$product_id]['stock']['shipout'] = $stock['active_total'];
$products[$product_id]['box_max'] = ceil($stock['active_total'] / $product['boxAmount']);
} else {
$products[$product_id]['stock']['shipout'] = 0;
}
}
}
}
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_address', '進貨地址', 'required|max_length[200]');
$this->form_validation->set_rules('shipin_address', '收貨地址', 'required|max_length[200]');
if (!empty($_POST['isInvoice'])) {
$this->form_validation->set_rules('invoice_retailer_id', '發票對象', 'integer|in_list[' . implode(',', array_keys($invoice_retailers)) . ']');
$this->form_validation->set_rules('invoice_retailer', '發票對象', 'required|max_length[200]');
$this->form_validation->set_rules('invoice_send_retailer_id', '發票寄送對象', 'integer|in_list[' . implode(',', array_keys($invoice_send_retailers)) . ']');
$this->form_validation->set_rules('invoice_send_retailer', '發票寄送對象', 'required|max_length[200]');
$this->form_validation->set_rules('invoice_send_address', '發票寄送地址', 'required|max_length[200]');
}
$this->form_validation->set_rules('items[][qty]', '訂購數量', 'callback_check_total[' . json_encode(['products' => $products, 'items' => $this->input->post('items')]) . ']');
if ($this->form_validation->run() !== FALSE) {
$purchaseSerialNum = $this->purchase_model->getNextPurchaseSerialNum();
//收貨對象與進貨單位不同
if ($shipin_retailer_id != $this->dealer['retailer_id']){
$new_retailer_id = $shipin_retailer_id;
$new_retailer_address = $this->input->post('shipin_address');
$new_shipout_retailer_id = $this->dealer['retailer_id'];
if (!empty($_POST['isInvoice'])) {
$relative_invoice_retailer = $this->retailer_relationship_model
->where('relation_type', 'invoice')
->where('retailer_id', $new_retailer_id)
->where('relation_retailer_id', $new_shipout_retailer_id)
->where('alter_retailer_id', $new_retailer_id)
->get();
if ($relative_invoice_retailer){
if ($relative_invoice_retailer['discount']){
$discount = $relative_invoice_retailer['discount'];
}
}
}
} else {
$new_retailer_id = $this->dealer['retailer_id'];
$new_retailer_address = $this->input->post('retailer_address');
$new_shipout_retailer_id = $shipout_retailer_id;
if (!empty($_POST['isInvoice']) && !empty($invoice_retailers[$this->input->post('invoice_retailer_id')]['discount'])) {
$discount = $invoice_retailers[$this->input->post('invoice_retailer_id')]['discount'];
}
}
$insert_data = [
'retailer_id' => $new_retailer_id,
'retailer_address' => $new_retailer_address,
'shipout_retailer_id' => $new_shipout_retailer_id,
'shipin_retailer_id' => $shipin_retailer_id,
'shipin_address' => $this->input->post('shipin_address'),
'serialNum' => $purchaseSerialNum,
'purchaseNum' => date('Ym') . $purchaseSerialNum,
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'isInvoice' => empty($_POST['isInvoice']) ? 0 : 1,
'dealer_id' => $this->dealer['id'],
];
if (!empty($_POST['isInvoice'])) {
$insert_data['invoice_retailer'] = $this->input->post('invoice_retailer');
$insert_data['invoice_send_retailer'] = $this->input->post('invoice_send_retailer');
$insert_data['invoice_send_address'] = $this->input->post('invoice_send_address');
}
$purchase_id = $this->purchase_model->insert($insert_data);
$subtotal = 0;
$total = 0;
$items = (array)$this->input->post('items');
$isMatchBox = false;
foreach ($items as $product_id => $item) {
$qty = $item['qty'];
if ($qty > 0) {
$price = $products[$product_id]['pdCash'];
$item_discount = empty($relationship_products[$product_id]) ? $discount : $relationship_products[$product_id];
$item_subtotal = $price * $qty;
$item_total = floor($price * $item_discount / 100) * $qty;
$this->purchase_item_model->insert([
'purchase_id' => $purchase_id,
'product_id' => $product_id,
'price' => $price,
'qty' => $qty,
'subtotal' => $price * $qty,
'discount' => $item_discount,
'total' => $item_total,
]);
if ($item['qty'] % $products[$product_id]['boxAmount'] == 0) {
$isMatchBox = true;
}
$subtotal += $item_subtotal;
$total += $item_total;
}
}
$this->purchase_model->update([
'isMatchBox' => $isMatchBox,
'subtotal' => $subtotal,
'total' => $total,
], ['id' => $purchase_id]);
$this->load->model('payment_model');
$this->payment_model->insert([
'pay_type' => 'purchase',
'pay_id' => $purchase_id,
'paid_retailer_id' => $new_retailer_id,
'received_retailer_id' => $new_shipout_retailer_id,
'price' => $total,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
'active' => 0,
]);
//收貨對象與進貨單位不同
if ($shipin_retailer_id != $this->dealer['retailer_id']){
//目前使用者單位向出貨單位採購
$new_purchase_id = $this->purchase_model->transfer_purchase($purchase_id, $shipout_retailer_id, $this->dealer);
if ($new_purchase_id){
if ($show_price) {
redirect(base_url('/purchase/detail/' . $new_purchase_id));
} else {
redirect(base_url('/purchase/detail2/' . $new_purchase_id));
}
}
}
if ($show_price) {
redirect(base_url('/purchase/detail/' . $purchase_id));
} else {
redirect(base_url('/purchase/detail2/' . $purchase_id));
}
}
}
}
}
$this->load->helper('form');
$data = [
'shipin_retailer_id' => $shipin_retailer_id,
'shipin_retailers' => $shipin_retailers,
'shipout_retailer_id' => $shipout_retailer_id,
'shipout_retailers' => $shipout_retailers,
'invoice_retailers' => $invoice_retailers,
'invoice_send_retailers' => $invoice_send_retailers,
'products' => $products,
'discount' => $discount,
'show_price' => $show_price,
'purchase_url' => $show_price ? base_url('purchase/add/') : base_url('purchase/add2/'),
'title' => '新增進貨單',
'view' => 'purchase/add',
];
$this->_preload($data);
}
public function check_total($i, $params)
{
$params = json_decode($params, true);
$products = $params['products'];
$items = $params['items'];
$totalQty = 0;
$subtotal = 0;
$error = '';
foreach ($items as $product_id => $item) {
if (!isset($products[$product_id])) {
$error = '輸入的貨品有誤';
break;
}
if ($item['qty'] % $products[$product_id]['step']){
$error = '輸入的貨品數量必須為包裝數量倍數';
break;
}
$subtotal += $item['qty'] * $products[$product_id]['pdCash'];
$totalQty += intval($item['qty']);
}
if (!$totalQty) {
$error = '您尚未選購商品';
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_total', $error);
return false;
}
}
public function edit($purchase_id)
{
$purchase = $this->purchase_model
->with_items(['with' =>
[
'relation' => 'product',
]
])
->where('retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無進貨單資料!');
}
if ($purchase['isConfirmed']){
show_error('此進貨單已確認');
}
if ($this->input->post()) {
$this->form_validation->set_rules('created_at', '進貨日期', 'required|valid_date');
if ($this->form_validation->run() !== FALSE) {
$items = (array)$this->input->post('items');
$subtotal = 0;
$total = 0;
foreach ($purchase['items'] as $i) {
$product_id = $i['product_id'];
$qty = $i['qty'];
$price = $items[$product_id]['price'];
$discount = $items[$product_id]['discount'];
$item_subtotal = $price * $qty;
$item_total = floor($price * $discount / 100) * $qty;
$this->purchase_item_model->update([
'price' => $price,
'subtotal' => $item_subtotal,
'discount' => $discount,
'total' => $item_total,
], ['id' => $i['id']]);
$subtotal += $item_subtotal;
$total += $item_total;
}
$this->purchase_model->update([
'subtotal' => $subtotal,
'total' => $total,
'created_at' => $this->input->post('created_at'),
], ['id' => $purchase_id]);
$this->load->model('payment_model');
$payments = $this->payment_model
->where('pay_type', 'purchase')
->where('pay_id', $purchase_id)
->get_all();
if ($payments) {
foreach ($payments as $payment) {
$this->payment_model->update([
'price' => $total,
], ['id' => $payment['id']]);
}
}
redirect(base_url('/purchase/detail/' . $purchase_id));
}
}
$data = [
'purchase' => $purchase,
'title' => '編輯進貨單',
'view' => 'purchase/edit',
];
$this->_preload($data);
}
public function cancel($purchase_id)
{
$purchase = $this->purchase_model
->where('retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無進貨單資料!');
}
if ($purchase['isShipped']) {
show_error('進貨單已經出貨不能取消');
}
$this->purchase_model->delete($purchase_id);
$this->purchase_model->update([
'transfer_id' => null,
], ['transfer_id' => $purchase_id]);
$this->load->model('payment_model');
$this->payment_model
->where('pay_type', 'purchase')
->where('pay_id', $purchase_id)
->where('active', 0)
->delete();
redirect(base_url('/purchase/overview'));
}
}
?><file_sep>/application/migrations/059_update_stock_counting_expiry_date.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_stock_counting_expiry_date extends CI_Migration {
public function up()
{
$this->dbforge->add_column('olive_stock_counting_items', [
'expired_at' => [
'type' => 'date',
'null' => TRUE,
'after' => 'stock',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_stock_counting_items', 'expired_at');
}
}<file_sep>/application/libraries/Stock_lib.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Stock_lib
{
var $CI;
public function __construct()
{
$this->CI =& get_instance();
$this->CI->load->model('product_model');
$this->CI->load->model('stock_model');
}
//直接調整經銷商產品庫存
public function retailer_adjust_stock($retailer_id, $product_id, $qty, $date = null)
{
$retailer = $this->getRetailer($retailer_id);
if (!$retailer) return false;
if ($this->isChange_retailer_stock($retailer)) {
$this->adjust_retailer_stock($retailer_id, $product_id, $qty, $date);
}
return true;
}
//出貨確定時事件
public function shipout_confirm($shipment_id)
{
$shipment = $this->getShipment($shipment_id);
if (!$shipment) return false;
$retailer_id = $shipment['shipout_retailer_id'];
if (!empty($shipment['expirations'])) {
foreach ($shipment['expirations'] as $expiration) {
if ($this->isChange_retailer_stock($shipment['shipout_retailer'])) {
$this->adjust_retailer_stock($retailer_id, $expiration['product_id'], ($expiration['qty'] * -1), $expiration['expired_at']);
}
}
}
return true;
}
//出貨取消時事件
public function shipout_rollback($shipment_id)
{
$shipment = $this->getShipment($shipment_id);
if (!$shipment) return false;
$retailer_id = $shipment['shipout_retailer_id'];
if (!empty($shipment['expirations'])) {
foreach ($shipment['expirations'] as $expiration) {
if ($this->isChange_retailer_stock($shipment['shipout_retailer'])) {
$this->adjust_retailer_stock($retailer_id, $expiration['product_id'], $expiration['qty'], $expiration['expired_at']);
}
}
}
return true;
}
//收貨確定時事件
public function shipin_confirm($shipment_id)
{
$shipment = $this->getShipment($shipment_id);
if (!$shipment) return false;
$retailer_id = $shipment['shipin_retailer_id'];
if (!empty($shipment['expirations'])) {
foreach ($shipment['expirations'] as $expiration) {
if ($this->isChange_retailer_stock($shipment['shipin_retailer'])) {
$this->adjust_retailer_stock($retailer_id, $expiration['product_id'], $expiration['qty'], $expiration['expired_at']);
}
}
}
return true;
}
//收貨取消時事件
public function shipin_rollback($shipment_id)
{
$shipment = $this->getShipment($shipment_id);
if (!$shipment) return false;
$retailer_id = $shipment['shipin_retailer_id'];
if (!empty($shipment['expirations'])) {
foreach ($shipment['expirations'] as $expiration) {
if ($this->isChange_retailer_stock($shipment['shipin_retailer'])) {
$this->adjust_retailer_stock($retailer_id, $expiration['product_id'], ($expiration['qty'] * -1), $expiration['expired_at']);
}
}
}
return true;
}
public function getShipment($shipment_id)
{
$this->CI->load->model('shipment_model');
return $this->CI->shipment_model
->with_shipout_retailer()
->with_shipin_retailer()
->with_expirations()
->get($shipment_id);
}
public function getRetailer($retailer_id)
{
$this->CI->load->model('retailer_model');
return $this->CI->retailer_model
->get($retailer_id);
}
//檢查進出貨單位是否有計算庫存
public function isChange_retailer_stock($shipment_retailer)
{
if (!empty($shipment_retailer) && $shipment_retailer['hasStock']){
return true;
}
return false;
}
//檢查進出貨單位是否會計算總庫存
public function isChange_total_stock($shipment_retailer)
{
if (!empty($shipment_retailer) && $shipment_retailer['totalStock']){
return true;
}
return false;
}
//單位庫存調整數量,qty可負數
public function adjust_retailer_stock($retailer_id, $product_id, $qty, $date = null)
{
if (!$retailer_id || !$product_id){
return false;
}
$qty = intval($qty);
if ($date){
$this->CI->stock_model->where('expired_at', $date);
} else {
$this->CI->stock_model->where('expired_at IS NULL', null, null, false, false, true);
}
$stock = $this->CI->stock_model
->where('retailer_id', $retailer_id)
->where('product_id', $product_id)
->get();
if ($stock) {
$qty = $stock['stock'] + $qty;
$this->CI->stock_model->update(
[
'stock' => $qty
],
['id' => $stock['id']]
);
} else {
$this->CI->stock_model->insert([
'retailer_id' => $retailer_id,
'product_id' => $product_id,
'stock' => $qty,
'expired_at' => $date,
]);
}
return true;
}
//直接給單位庫存數量
public function retailer_stock_value($retailer_id, $product_id, $qty, $date = null)
{
if (!$retailer_id || !$product_id){
return false;
}
$qty = intval($qty);
if ($date){
$this->CI->stock_model->where('expired_at', $date);
} else {
$this->CI->stock_model->where('expired_at IS NULL', null, null, false, false, true);
}
$stock = $this->CI->stock_model
->where('retailer_id', $retailer_id)
->where('product_id', $product_id)
->get();
if ($stock) {
$this->CI->stock_model->update([
'stock' => $qty
], ['id' => $stock['id']]);
} else {
$this->CI->stock_model->insert([
'retailer_id' => $retailer_id,
'product_id' => $product_id,
'stock' => $qty,
'expired_at' => $date,
]);
}
return true;
}
}
?><file_sep>/application/models/Bad_login_model.php
<?php
class Bad_login_model extends MY_Model{
public $table = 'bad_login';
public $primary_key = 'autoid';
function __construct(){
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
}
}
?>
<file_sep>/application/migrations/019_add_expense.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_expense extends CI_Migration
{
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'event_type' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => TRUE,
],
'event_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'expense_type' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => TRUE,
],
'price' => [
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
],
'dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_expenses');
}
public function down()
{
$this->dbforge->drop_table('olive_expenses');
}
}<file_sep>/application/models/Stock_counting_item_model.php
<?php
class Stock_counting_item_model extends MY_Model
{
public $table = 'olive_stock_counting_items';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['stock_counting'] = array('foreign_model' => 'Stock_counting_model', 'foreign_table' => 'olive_stock_countings', 'foreign_key' => 'id', 'local_key' => 'stock_counting_id');
$this->has_one['product'] = array('foreign_model' => 'Product_model', 'foreign_table' => 'product', 'foreign_key' => 'pdId', 'local_key' => 'product_id');
}
}
?>
<file_sep>/application/views/capital/relationship/invoice/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增發票關係單位</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>出貨單位</label>
<?php
echo form_dropdown('relation_retailer_id', ['' => ''] + $retailer_selects, set_value('relation_retailer_id'), 'class="form-control required"');
?>
</div>
<div class="form-group">
<label>發票單位</label>
<?php
echo form_dropdown('alter_retailer_id', ['' => ''] + $retailer_selects, set_value('alter_retailer_id'), 'class="form-control required"');
?>
</div>
<div class="form-group">
<label class="font-weight-bold">折扣</label>
<div class="input-group">
<input type="number" name="discount" class="form-control text-right" max="100" min="1" value="<?= set_value('discount') ?>"/>
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_relationship_invoice/overview/' . $retailer['id'])?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/purchase/add.php
<div class="container">
<h1 class="mb-4 text-center">新增進貨單</h1>
<form method="post" id="purchaseForm">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">訂貨日期</label>
<div class="col-sm-10">
<input readonly class="form-control-plaintext" value="<?= date('Y-m-d') ?>">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">出貨單位</label>
<div class="col-sm-10">
<?php if (count($shipout_retailers) == 1) { ?>
<?= current($shipout_retailers)['company'] ?>
<input type="hidden" id="shipout_retailer_id" value="<?= $shipout_retailer_id ?>"/>
<?php } else { ?>
<select id="shipout_retailer_id" name="shipout_retailer_id" class="form-control">
<option value=""></option>
<?php foreach ($shipout_retailers as $retailer_id => $retailer) { ?>
<option value="<?= $retailer_id ?>" <?php if (!empty($shipout_retailer_id) && $retailer_id == $shipout_retailer_id) {
echo 'selected';
} ?>><?= $retailer['company'] ?></option>
<?php } ?>
</select>
<?php } ?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">進貨單位</label>
<div class="col-sm-10">
<?= $dealer['company'] ?>
<input type="hidden" id="retailer_id" value="<?=$dealer['retailer_id']?>" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">進貨單位地址</label>
<div class="col-sm-10">
<input name="retailer_address" class="form-control" value="<?= $dealer['address'] ?>" required placeholder="自行輸入進貨單位地址" />
</div>
</div>
<?php if (!empty($shipout_retailer_id)) { ?>
<?php if ($shipin_retailers){ ?>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">收貨對象</label>
<div class="col-sm-10">
<?php if (count($shipin_retailers) == 1) { ?>
<?= current($shipin_retailers)['invoice_title'] ?>
<input type="hidden" id="shipin_retailer_id" value="<?= $shipin_retailer_id ?>"/>
<?php } else { ?>
<select id="shipin_retailer_id" name="shipin_retailer_id" class="form-control" required>
<option value=""></option>
<?php foreach ($shipin_retailers as $retailer_id => $retailer) { ?>
<option value="<?= $retailer_id ?>" data-address="<?= $retailer['address'] ?>" <?php if (!empty($shipin_retailer_id) && $retailer_id == $shipin_retailer_id) {
echo 'selected';
} ?>><?= $retailer['invoice_title'] ?></option>
<?php } ?>
</select>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if (!empty($shipin_retailer_id)) { ?>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">收貨地址</label>
<div class="col-sm-10">
<input name="shipin_address" class="form-control" value="<?= $shipin_retailers[$shipin_retailer_id]['address'] ?>" required placeholder="自行輸入收貨地址" />
</div>
</div>
<?php if ($shipin_retailer_id != 2 || $shipout_retailer_id != 1) { ?>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">開立發票</label>
<div class="col-sm-10">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name="isInvoice" id="isInvoice"
value="1">
<label class="form-check-label" for="isInvoice">需開立發票</label>
</div>
</div>
</div>
<?php } else { ?>
<input type="hidden" name="isInvoice" value="1">
<?php } ?>
<?php if ($invoice_retailers){ ?>
<div id="invoice_container" class="<?php if ($shipin_retailer_id != 2 || $shipout_retailer_id != 1){ echo 'd-none';} ?>">
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">發票對象</label>
<div class="col-sm-10">
<div class="input-group">
<select id="invoice_retailer_id" name="invoice_retailer_id" class="form-control">
<option value="">自行輸入</option>
<?php foreach ($invoice_retailers as $retailer_id => $retailer) { ?>
<option value="<?= $retailer_id ?>" data-discount="<?= $retailer['discount'] ?>" <?php if ($retailer_id == $shipin_retailer_id){ echo 'selected'; } ?>><?= $retailer['invoice_title'] ?></option>
<?php } ?>
</select>
<input id="invoice_retailer" name="invoice_retailer" class="form-control <?php if ($invoice_retailers) { echo 'd-none'; } ?>" required value="<?=$shipin_retailers[$shipin_retailer_id]['invoice_title']?>" placeholder="自行輸入發票對象" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">發票寄送對象</label>
<div class="col-sm-10">
<div class="input-group">
<select id="invoice_send_retailer_id" name="invoice_send_retailer_id" class="form-control">
<option value="">自行輸入</option>
<?php foreach ($invoice_send_retailers as $retailer_id => $retailer) { ?>
<option value="<?= $retailer_id ?>" data-address="<?= $retailer['address'] ?>" <?php if ($retailer_id == $shipin_retailer_id){ echo 'selected'; } ?>><?= $retailer['invoice_title'] ?></option>
<?php } ?>
</select>
<input id="invoice_send_retailer" name="invoice_send_retailer" class="form-control <?php if ($invoice_send_retailers) { echo 'd-none'; } ?>" required value="<?=$shipin_retailers[$shipin_retailer_id]['invoice_title']?>" placeholder="自行輸入發票寄送對象" />
</div>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">發票寄送地址</label>
<div class="col-sm-10">
<input id="invoice_send_address" name="invoice_send_address" class="form-control" value="<?=$shipin_retailers[$shipin_retailer_id]['address']?>" required placeholder="自行輸入發票寄送地址" />
</div>
</div>
</div>
<?php } ?>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">進貨方之備註</label>
<div class="col-sm-10">
<textarea rows="4" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
</div>
</div>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
<th>出貨單位庫存</th>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<th>進貨單位庫存</th>
<?php } ?>
<th>單價(含稅)</th>
<th>包裝數量</th>
<th>訂購數量</th>
<?php if ($show_price){ ?>
<th>金額小計</th>
<th>折扣</th>
<th>折扣價</th>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<th>進貨單位新庫存量</th>
<?php } ?>
</tr>
<?php if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td><?= $product['p_num'] ?></td>
<td>
<?= $product['pdName'] ?> <?= $product['intro2'] ?>
<?php if ($product['picture']) { ?>
<a class="show_picture" data-toggle="tooltip"
title="<img src='<?= $product['picture'] ?>' />">
<i class="far fa-images"></i>
</a>
<?php } ?>
</td>
<?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
<td class="text-right"><?= $product['stock']['shipout'] ?></td>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<td class="text-right"><?= $product['stock']['shipin'] ?></td>
<?php } ?>
<td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
<td class="text-right"><?= $product['boxAmount'] ?></td>
<td>
<input type="number" name="items[<?= $product_id ?>][qty]"
min="0" class="itemQty form-control text-right"
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
data-shipin-stock="<?= intval($product['stock']['shipin']) ?>"
<?php } ?>
data-boxamount="<?= intval($product['boxAmount']) ?>"
data-price="<?= intval($product['pdCash']) ?>"
data-discount="<?= intval($product['discount']) ?>"
step="<?= $product['step'] ?>"
value="<?= set_value('items[' . $product_id . '][qty]') ?>"
style="width: 120px;"
/>
</td>
<?php if ($show_price){ ?>
<td class="item_subtotal text-right"></td>
<td class="item_discount text-right"></td>
<td class="item_total text-right"></td>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<td class="item_stock text-right"></td>
<?php } ?>
</tr>
<?php
$i++;
}
}
?>
<tr>
<td colspan="3"></td>
<?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
<td></td>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<td></td>
<?php } ?>
<td colspan="2" class="text-right font-weight-bold">小計</td>
<td id="total_qty_text" class="text-right font-weight-bold"></td>
<?php if ($show_price){ ?>
<td id="total_subtotal_text" class="text-right font-weight-bold"></td>
<td></td>
<td id="total_text" class="text-right font-weight-bold"></td>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<td id="total_stock_text" class="text-right font-weight-bold"></td>
<?php } ?>
</tr>
<tr>
<td colspan="3"></td>
<?php if ($shipout_retailers[$shipout_retailer_id]['hasStock']) { ?>
<td></td>
<?php } ?>
<?php if ($shipin_retailers[$shipin_retailer_id]['hasStock']) { ?>
<td></td>
<?php } ?>
<td colspan="7"></td>
</tr>
</table>
<div class="form-group text-center">
<input type="submit" class="btn btn-success" value="送出進貨單" />
<input type="hidden" id="shipout_hasStock" value="<?= $shipout_retailers[$shipout_retailer_id]['hasStock'] ?>" />
<input type="hidden" id="shipin_hasStock" value="<?= $shipin_retailers[$shipin_retailer_id]['hasStock'] ?>" />
<input type="hidden" id="totalQty" value="0" />
<input type="hidden" id="subtotal" value="0" />
<input type="hidden" id="discount" value="<?=$discount?>" />
</div>
<?php } ?>
<?php } ?>
</form>
</div>
<script>
$().ready(function () {
calc_total();
$('a.show_picture').tooltip({
animated: 'fade',
placement: 'top',
html: true
});
$('#shipout_retailer_id').change(function () {
var shipout_retailer_id = parseInt($(this).val()) || 0;
if (shipout_retailer_id > 0) {
window.location = '<?=$purchase_url ?>' + shipout_retailer_id;
} else {
window.location = '<?=$purchase_url ?>';
}
});
$('#shipin_retailer_id').change(function () {
var shipout_retailer_id = parseInt($('#shipout_retailer_id').val()) || 0;
var shipin_retailer_id = parseInt($(this).val()) || 0;
if (shipout_retailer_id > 0 && shipin_retailer_id > 0) {
window.location = '<?=$purchase_url ?>' + shipout_retailer_id + '/' + shipin_retailer_id;
} else {
window.location = '<?=$purchase_url ?>' + shipout_retailer_id;
}
});
$('#invoice_retailer_id').change(function () {
var invoice_retailer_id = parseInt($(this).val()) || 0;
if (invoice_retailer_id > 0) {
$('#invoice_retailer').val($(this).find('option:selected').text()).addClass('d-none');
} else {
$('#invoice_retailer').val('').removeClass('d-none');
}
calc_total();
});
$('#invoice_send_retailer_id').change(function () {
var invoice_send_retailer_id = parseInt($(this).val()) || 0;
if (invoice_send_retailer_id > 0) {
$('#invoice_send_retailer').val($(this).find('option:selected').text()).addClass('d-none');
$('#invoice_send_address').val($(this).find('option:selected').data('address'));
} else {
$('#invoice_send_retailer').val('').removeClass('d-none');
$('#invoice_send_address').val('');
}
});
$('#isInvoice').change(function(){
if ($(this).prop("checked")){
$('#invoice_container').removeClass('d-none');
} else {
$('#invoice_container').addClass('d-none');
}
});
$('#fare').change(function(e){
if (!confirm('是否確定更改運費?')){
$('#fare').val(0);
}
});
$('#purchaseForm input.itemQty').change(function () {
calc_total();
});
function calc_total() {
var totalShipinStock = 0;
var totalQty = 0;
var subtotal = 0;
var shipout_hasStock = $('#shipout_hasStock').val();
var shipin_hasStock = $('#shipin_hasStock').val();
$('#purchaseForm input.itemQty').each(function () {
var item = $(this).parents('tr');
var qty = parseInt($(this).val()) || 0;
var price = parseInt($(this).data('price'));
var shipin_stock = parseInt($(this).data('shipin-stock'));
if (qty > 0) {
item.find('.item_subtotal').text('$' + numberWithCommas(price * qty));
totalQty += qty;
subtotal += price * qty;
if (shipin_hasStock){
item.find('.item_stock').text(shipin_stock + qty);
totalShipinStock += shipin_stock;
}
} else {
item.find('.item_subtotal').text('');
if (shipin_hasStock) {
item.find('.item_stock').text('');
}
}
});
$('#total_qty_text').text(numberWithCommas(totalQty));
$('#totalQty').val(totalQty);
$('#total_subtotal_text').text('$' + numberWithCommas(subtotal));
$('#subtotal').val(subtotal);
if (shipin_hasStock) {
$('#total_stock_text').text(numberWithCommas((totalQty + totalShipinStock)));
}
calc_discount();
}
function calc_discount() {
var total = 0;
var discount = parseInt($('#discount').val()) || 100;
if (($('input[type="checkbox"][name="isInvoice"]').length && $('input[type="checkbox"][name="isInvoice"]').prop('checked') == true) || $('input[type="hidden"][name="isInvoice"]').length) {
var retailer_id = parseInt($('#retailer_id').val());
var shipin_retailer_id = parseInt($('#shipin_retailer_id').val());
if (retailer_id == shipin_retailer_id) {
var invoice_retailer_discount = $('#invoice_retailer_id').find('option:selected').data('discount');
if (invoice_retailer_discount != undefined && invoice_retailer_discount > 0) {
discount = parseInt(invoice_retailer_discount);
}
}
}
if (discount > 100){
discount = 100;
}
$('#purchaseForm input.itemQty').each(function () {
var item = $(this).parents('tr');
var qty = parseInt($(this).val()) || 0;
var price = parseInt($(this).data('price'));
var item_discount = $(this).data('discount') ? parseInt($(this).data('discount')) : discount;
var discount_text = item_discount + '%';
item.find('td.item_discount').text(discount_text);
if (qty > 0) {
var discount_price = Math.floor(price * item_discount / 100) * qty;
item.find('td.item_total').text('$' + numberWithCommas(discount_price));
total += discount_price;
} else {
item.find('td.item_total').text('');
}
});
$('#total_text').text('$' + numberWithCommas(total));
}
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
$("#purchaseForm").keydown(function(e){
if(e.keyCode == 13) {
e.preventDefault();
return false;
}
});
$("#purchaseForm").submit(function (e) {
var subtotal = parseInt($('#subtotal').val()) || 0;
var totalQty = parseInt($('#totalQty').val()) || 0;
if (totalQty == 0) {
alert('請至少進貨一樣商品!');
return false;
}
var match_boxamount = true;
$('#purchaseForm input.itemQty').each(function () {
var qty = parseInt($(this).val());
var boxamount = parseInt($(this).data('boxamount'));
if (qty > 0 && qty % boxamount !== 0){
match_boxamount = false;
return false;
}
});
var is_confirm = false;
if (!match_boxamount){
if (confirm('此單非全部都是整箱的倍數的數量,取貨方式限定親自至輔銷單位取貨')){
is_confirm = true;
} else {
return false;
}
} else {
is_confirm = true;
}
if (is_confirm) {
$.each($('input.itemQty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
}
});
</script><file_sep>/application/controllers/Capital_retailer_role.php
<?php
class Capital_retailer_role extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_role_model');
$this->session->set_userdata('return_page', base_url('/capital_retailer_role/overview'));
}
public function overview()
{
$roles = $this->retailer_role_model
->with_level_types()
->order_by('id', 'asc')
->get_all();
$data = [
'roles' => $roles,
'title' => '單位類型總覽',
'view' => 'capital/retailer/role/overview',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/capital/product/relationship/edit.php
<div class="container">
<h1 class="mb-4">編輯<?= $relationship['relation']['company'] ?>至<?= $relationship['retailer']['company'] ?>的產品折扣</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價</th>
<th>折扣 (預設<?=$relationship['discount']?>%)</th>
</tr>
<?php
if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
?>
<tr>
<td class="text-center"><?= $i ?></td>
<td><?= $product['p_num'] ?></td>
<td>
<?= $product['pdName'] ?> <?= $product['intro2'] ?>
</td>
<td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
<td>
<input type="number" name="items[<?= $product_id ?>][discount]"
min="1" max="100" class="form-control text-right"
value="<?= set_value('items[' . $product_id . '][discount]', isset($product_relationships[$product_id]) ? $product_relationships[$product_id]['discount'] : '') ?>"
/>
</td>
</tr>
<?php
$i++;
}
}
?>
</table>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_relationship_shipout/overview/' . $relationship['retailer_id'])?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div><file_sep>/application/controllers/Capital_product_permission.php
<?php
class Capital_product_permission extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('product_model');
$this->load->model('product_permission_model');
$this->session->set_userdata('return_page', base_url('/capital_product_permission/overview'));
}
public function edit($product_id)
{
$product = $this->product_model
->get($product_id);
if (!$product_id || !$product) {
show_error('查無商品資料');
}
$permission = $this->product_permission_model
->where('product_id', $product_id)
->get();
if (!$permission){
$permission_id = $this->product_permission_model->insert([
'product_id' => $product_id,
]);
$permission = [
'id' => $permission_id,
'product_id' => $product_id,
'retailers' => [],
'remark' => '',
];
} else {
$permission['retailers'] = explode(',', $permission['include_retailers']);
}
if ($this->input->post()) {
$this->form_validation->set_rules('remark', '備註', 'max_length[200]');
if ($this->form_validation->run() !== FALSE) {
$include_retailers = (array)$this->input->post('include_retailers');
$this->product_permission_model->update([
'include_retailers' => $include_retailers ? implode(',', $include_retailers) : null,
'remark' => $this->input->post('remark'),
], ['id' => $permission['id']]);
redirect(base_url('/capital_product/overview/'));
}
}
$retailer_selects = $this->retailer_model->getRetailerSelect();
$data = [
'permission' => $permission,
'retailers' => $retailer_selects,
'product' => $product,
'title' => '編輯進貨商品',
'view' => 'capital/product/permission/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/capital/product/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增商品</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>貨品編號</label>
<input name="p_num" class="form-control" value="<?= set_value('p_num') ?>" required />
</div>
<div class="form-group">
<label>名稱</label>
<input name="pdName" class="form-control" value="<?= set_value('pdName') ?>" required />
</div>
<div class="form-group">
<label>外緣尺寸</label>
<input name="intro2" class="form-control" value="<?= set_value('intro2') ?>" required />
</div>
<div class="form-group">
<label>商品分類</label>
<?php
echo form_dropdown('pKind', $kind_selects, set_value('pKind'), 'class="form-control" required');
?>
</div>
<div class="form-group">
<label>單價</label>
<input type="number" name="pdCash" class="form-control" value="<?= set_value('pdCash') ?>" required min="0" />
</div>
<div class="form-group">
<label>每箱數量</label>
<input type="number" name="boxAmount" class="form-control" value="<?= set_value('boxAmount') ?>" required min="1" />
</div>
<div class="form-group">
<label>有效期限</label>
<?php
echo form_dropdown('pao_id', ['' => ''] + $pao_selects, set_value('pao_id'), 'class="form-control" required');
?>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_product/overview/')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/capital/level/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">更新經銷規則</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>類別</label>
<input name="type" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
</div>
<div class="form-group">
<label>代碼</label>
<input name="code" class="form-control" value="<?= $level['code'] ?>" required />
</div>
<div class="form-group">
<label>名稱</label>
<input name="title" class="form-control-plaintext" value="<?= $level['type']['title'] ?>"/>
</div>
<div class="form-group">
<label>折扣</label>
<div class="input-group">
<input type="number" name="discount" class="form-control text-right" required max="100" min="1" value="<?= set_value('discount', $level['discount']) ?>"/>
<div class="input-group-append">
<span class="input-group-text">%</span>
</div>
</div>
</div>
<div class="form-group">
<label>首次進貨門檻</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" name="firstThreshold" class="form-control text-right" value="<?= set_value('firstThreshold', $level['firstThreshold']) ?>"/>
</div>
</div>
<div class="form-group">
<label>每月進貨門檻</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" name="monthThreshold" class="form-control text-right" value="<?= set_value('monthThreshold', $level['monthThreshold']) ?>"/>
</div>
</div>
<div class="form-group">
<label>保證金</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="number" name="guarantee" class="form-control text-right" min="0" required value="<?= set_value('guarantee', $level['guarantee']) ?>"/>
</div>
</div>
<div class="form-group">
<label>補充說明</label>
<textarea id="remark" name="remark" class="form-control"><?= set_value('remark', $level['remark']) ?></textarea>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_level/overview/')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div>
<script src="//cdn.ckeditor.com/4.9.1/standard/ckeditor.js"></script>
<script>
CKEDITOR.replace( 'remark', {
allowedContent : true,
extraAllowedContent : 'div(*)'
});
</script><file_sep>/application/views/customer/conv_old.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">舊有會員轉換</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>電話</label>
<input name="phone" class="form-control" required value="<?= set_value('phone', $customer['phone']) ?>"/>
</div>
<div class="form-group">
<label>姓名</label>
<input name="name" class="form-control" required value="<?= set_value('name', $customer['name']) ?>"/>
</div>
<div class="form-group">
<label>性別</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_1"
value="1"<?= set_value('gender', $customer['gender']) == '1' ? ' checked' : '' ?> required>
<label class="form-check-label" for="gender_1">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_0"
value="0"<?= set_value('gender', $customer['gender']) === '0' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_0">女</label>
</div>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">生日</label>
<div class="form-row">
<div class="col">
<select class="form-control" name="birthday_year">
<option value="">生日年</option>
<?php for ($i = date('Y'); $i > date('Y', strtotime('-100 years')); $i--){ ?>
<option value="<?=$i?>"<?php if (set_value('birthday_year') == $i){ echo ' selected'; } ?>><?=$i?></option>
<?php } ?>
</select>
</div>
<div class="col">
<input id="birthday" name="birthday" required class="form-control" value="<?= set_value('birthday') ?>"/>
</div>
</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" value="<?= set_value('email', $customer['email']) ?>"/>
</div>
<div class="form-group">
<label>地址</label>
<input name="address" class="form-control" required value="<?= set_value('address', $customer['address']) ?>"/>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/customer/old')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="轉換"/>
</div>
</form>
</div>
</div>
</div>
<link rel="stylesheet" href="<?= base_url('/css/datepicker.min.css')?>" />
<script src="<?= base_url('/js/datepicker.min.js')?>"></script>
<script>
$( function() {
$("#birthday").datepicker({
format: 'mm/dd'
});
} );
</script>
<file_sep>/application/helpers/export_csv_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if ( ! function_exists('array_to_csv')) {
function array_to_csv($data, $filename)
{
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=\"".$filename.".csv\"");
header("Pragma: no-cache");
header("Expires: 0");
$handle = fopen('php://output', 'w');
foreach ($data as $i) {
fputcsv($handle, $i, "\t");
}
fclose($handle);
}
}
<file_sep>/application/controllers/Capital_pao.php
<?php
class Capital_pao extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('pao_model');
$this->session->set_userdata('return_page', base_url('/capital_pao/overview'));
}
public function overview()
{
$total_paos_count = $this->pao_model
->count_rows();
$paos = $this->pao_model
->paginate(20, $total_paos_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_pao', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_pao', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_pao', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'paos' => $paos,
'pagination' => $this->pao_model->all_pages,
'authority' => $authority,
'title' => '商品期限參數總覽',
'view' => 'capital/pao/overview',
];
$this->_preload($data);
}
public function add()
{
if ($this->input->post()) {
$this->form_validation->set_rules('expiration_month', '有效期限', 'required|integer|greater_than_equal_to[1]');
$this->form_validation->set_rules('pao_month', 'PAO', 'required|integer|greater_than_equal_to[0]');
if ($this->form_validation->run() !== FALSE) {
$this->pao_model->insert([
'expiration_month' => $this->input->post('expiration_month'),
'pao_month' => $this->input->post('pao_month'),
]);
redirect(base_url('/capital_pao/overview/'));
}
}
$data = [
'title' => '新增商品期限參數',
'view' => 'capital/pao/add',
];
$this->_preload($data);
}
public function edit($pao_id)
{
$pao = $this->pao_model
->get($pao_id);
if (!$pao_id || !$pao) {
show_error('查無商品期限參數資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('expiration_month', '有效期限', 'required|integer|greater_than_equal_to[1]');
$this->form_validation->set_rules('pao_month', 'PAO', 'required|integer|greater_than_equal_to[0]');
if ($this->form_validation->run() !== FALSE) {
$this->pao_model->update([
'expiration_month' => $this->input->post('expiration_month'),
'pao_month' => $this->input->post('pao_month'),
], ['id' => $pao_id]);
redirect(base_url('/capital_pao/overview/'));
}
}
$data = [
'pao' => $pao,
'title' => '編輯商品期限參數',
'view' => 'capital/pao/edit',
];
$this->_preload($data);
}
public function cancel($pao_id)
{
$pao = $this->pao_model
->get($pao_id);
if (!$pao_id || !$pao) {
show_error('查無經銷商品資料');
}
$this->load->model('product_model');
$_products = $this->product_model
->where('pao_id', $pao_id)
->get_all();
if ($_products){
$products = [];
foreach ($_products as $p){
array_push($products, $p['pdName']);
}
show_error('商品(' . implode(', ', $products) . ')已經使用此效期,請先修改商品再刪除。');
}
$this->pao_model->delete($pao_id);
redirect(base_url('/capital_pao/overview/'));
}
}
?><file_sep>/application/controllers/Coupon.php
<?php
class Coupon extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged())) {
redirect(base_url('/'));
}
$this->load->model('coupon_model');
$this->load->model('confirm_model');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/coupon/overview'));
}
public function overview()
{
$end_month = date('Y-m-01', strtotime('+1 month'));
$start_month = date('Y-m-01', strtotime($end_month . ' -24 month'));
$_coupons = $this->coupon_model
->where('retailer_id', $this->dealer['retailer_id'])
->where('coupon_month', '>=', $start_month)
->where('coupon_month', '<=', $end_month)
->order_by('coupon_month', 'desc')
->get_all();
$coupons = [];
for ($i = 0; $i < 24; $i++){
$month = date('Y-m-01', strtotime($end_month . ' -' . $i .' month'));
$coupon = [
'coupon_month' => $month,
'qty' => '',
'first_couponNum' => '',
'last_couponNum' => '',
'receive_confirm' => null,
'receive_confirm_text' => null,
];
if ($_coupons){
foreach ($_coupons as $key => $c){
if ($c['coupon_month'] == $month){
$confirm = $this->confirm_model
->where('confirm_type', 'coupon')
->where('confirm_id', $c['id'])
->order_by('created_at', 'desc')
->get();
if ($confirm){
$c['receive_confirm'] = $confirm['audit'];
$c['receive_confirm_text'] = confirmStatus($confirm['audit']);
}
$coupon = $c;
unset($_coupons[$key]);
break;
}
}
}
$coupons[] = $coupon;
}
//權限設定
$authority = array();
// if ($this->authentic->authority('coupon', 'detail')){
// $authority['detail'] = true;
// }
if ($this->authentic->authority('coupon', 'edit')){
$authority['edit'] = true;
}
$data = [
'coupons' => $coupons,
'authority' => $authority,
'title' => '折價券核發紀錄',
'view' => 'coupon/overview',
];
$this->_preload($data);
}
// public function detail($coupon_id)
// {
// $coupon = $this->coupon_model
// ->with_approves(['with' => ['relation' => 'order', 'fields' => 'orderNum']])
// ->with_order()
// ->where('retailer_id', $this->dealer['retailer_id'])
// ->get($coupon_id);
//
// if (!$coupon_id || !$coupon){
// show_error('查無折價券資料');
// }
//
// $data = [
// 'coupon' => $coupon,
// 'title' => '核發記錄明細',
// 'view' => 'coupon/detail',
// ];
//
// $this->_preload($data);
// }
public function edit($id)
{
$coupon = [];
if ($id) {
$tmp = explode('_', $id);
if (!empty($tmp[0]) && $tmp[0] == 'month') {
if (!empty($tmp[1]) && strtotime($tmp[1]) > 0){
$coupon_month = date('Y-m-01', strtotime($tmp[1]));
$coupon = $this->coupon_model
->where('retailer_id', $this->dealer['retailer_id'])
->where('coupon_month', '=', $coupon_month)
->get();
if (!$coupon){
$coupon = [
'id' => '',
'coupon_month' => $coupon_month,
'qty' => 0,
'first_couponNum' => '',
'last_couponNum' => '',
];
}
}
} else {
$coupon_id = (int)$id;
$coupon = $this->coupon_model
->where('retailer_id', $this->dealer['retailer_id'])
->get($coupon_id);
}
}
if (!$coupon){
show_error('查無折價券資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('qty', '優惠券張數', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('first_couponNum', '首張優惠券序號', 'required|max_length[30]');
$this->form_validation->set_rules('last_couponNum', '末張優惠券序號', 'required|max_length[30]');
if ($coupon['id']){
$this->coupon_model->update([
'qty' => $this->input->post('qty'),
'first_couponNum' => $this->input->post('first_couponNum'),
'last_couponNum' => $this->input->post('last_couponNum'),
], ['id' => $coupon['id']]);
} else {
$coupon['id'] = $this->coupon_model->insert([
'retailer_id' => $this->dealer['retailer_id'],
'coupon_month' => $coupon['coupon_month'],
'qty' => $this->input->post('qty'),
'first_couponNum' => $this->input->post('first_couponNum'),
'last_couponNum' => $this->input->post('last_couponNum'),
]);
}
$this->confirm_model->insert([
'confirm_type' => 'coupon',
'confirm_id' => $coupon['id'],
'audit_retailer_id' => 2, //總經銷
'dealer_id' => $this->dealer['id'],
]);
redirect(base_url('/coupon/overview'));
}
$data = [
'coupon' => $coupon,
'title' => '貴賓優惠券序號登錄',
'view' => 'coupon/edit',
];
$this->_preload($data);
}
public function confirm()
{
$_confirm_group = $this->confirm_model
->fields('MAX(' . $this->confirm_model->get_table_name() . '.id) as id')
->where('confirm_type', 'coupon')
->where('audit_retailer_id', $this->dealer['retailer_id'])
->where('created_at', '>=', date('Y-m-d', strtotime('-180 days')))
->group_by('confirm_id')
->get_all();
$confirms = [];
if ($_confirm_group){
$confirm_group = [];
foreach ($_confirm_group as $cg){
array_push($confirm_group, $cg['id']);
}
$total_confirms_count = $this->confirm_model
->where('id', $confirm_group)
->where('confirm_type', 'coupon')
->where('audit_retailer_id', $this->dealer['retailer_id'])
->where('audit IS NULL', null, null, false, false, true)
->count_rows();
$confirms = $this->confirm_model
->with_coupon(['with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('id', $confirm_group)
->where('confirm_type', 'coupon')
->where('audit_retailer_id', $this->dealer['retailer_id'])
->where('audit IS NULL', null, null, false, false, true)
->paginate(20, $total_confirms_count);
}
//權限設定
$authority = array();
if ($this->authentic->authority('coupon', 'approved')){
$authority['approved'] = true;
}
$data = [
'confirms' => $confirms,
'pagination' => $this->confirm_model->all_pages,
'authority' => $authority,
'title' => '折價券審核',
'view' => 'coupon/confirm',
];
$this->_preload($data);
}
public function approved($confirm_id)
{
$confirm = $this->confirm_model
->with_coupon(['with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('confirm_type', 'coupon')
->where('audit_retailer_id', $this->dealer['retailer_id'])
->where('audit IS NULL', null, null, false, false, true)
->get($confirm_id);
if (!$confirm_id || !$confirm) {
show_error('查無審核資料');
}
if ($this->input->post()) {
$audit = 0;
if (isset($_POST['approved'])) {
$audit = 1;
}
$this->confirm_model->update([
'audit' => $audit,
], ['id' => $confirm_id]);
$this->session->set_userdata(array('msg' => '已經審核完畢'));
redirect(base_url('/coupon/confirm'));
}
$data = [
'confirm' => $confirm,
'title' => '折價券審核',
'view' => 'coupon/approved',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/consumer/old.php
<div class="container">
<h1 class="mb-4 text-center">舊有會員轉換</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="row justify-content-md-center">
<div class="col-md-8">
<div class="form-group">
<label class="font-weight-bold">舊有會員轉換說明</label>
<ul>
<li>舊有會員召回完成實名登記者即成為綠卡會員。</li>
<li>舊有會員一年消費未滿 12次或未單次購買12,000元於 實名登記完隔年降為飄雪白卡。</li>
<li>舊有會員達2年未消費,自動喪失會員資格。</li>
</ul>
</div>
<div class="form-group">
<label class="font-weight-bold">電話</label>
<input name="phone" class="form-control" required value="<?= set_value('phone') ?>"/>
</div>
</div>
</div>
<div class="form-group text-center">
<input type="submit" name="submit_buy" class="btn btn-success mr-2" value="查詢並購買"/>
<input type="submit" class="btn btn-success" value="查詢轉換"/>
</div>
</form>
</div>
</div><file_sep>/application/views/guest/admin_check_login.php
<div class="container">
<h1 class="mb-4">總監登入確認</h1>
<form method="post" id="purchaseForm">
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input class="form-control" name="account" required placeholder="總監代號">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-lock"></i></span>
</div>
<input type="<PASSWORD>" class="form-control" name="password" required placeholder="請輸入密碼">
</div>
</div>
<div class="form-group d-flex justify-content-between">
<input type="submit" value="登入" class="btn btn-lg btn-success"/>
</div>
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?php echo validation_errors(); ?>
</div>
<?php } ?>
</form>
</div><file_sep>/application/controllers/Migrate.php
<?php
//在Cli 目錄下指令php index.php migrate version XX
// XX為Migration版本號碼,1, 2, 3...
class Migrate extends CI_Controller
{
public function __construct()
{
parent::__construct();
if (!$this->input->is_cli_request()) {
show_error('你沒有權限使用');
}
$this->load->library('migration');
}
public function version($version)
{
if ($this->migration->version($version) === FALSE)
{
show_error($this->migration->error_string());
} else {
echo 'Migration 成功';
}
}
}
?><file_sep>/application/controllers/Capital_promote_method.php
<?php
class Capital_promote_method extends MY_Controller
{
protected $dealer;
protected $promote_type;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('promote_model');
$this->load->model('promote_method_model');
$this->load->model('promote_item_model');
$this->load->model('promote_item_relative_model');
$this->load->model('product_model');
$this->load->model('combo_model');
$this->promote_type = [
1 => "產品折扣",
2 => "滿額折扣",
3 => "贈品",
];
$this->session->set_userdata('return_page', base_url('/capital_promote/overview'));
}
public function overview($promote_id)
{
$promote = $this->promote_model
->get($promote_id);
if (!$promote_id || !$promote) {
show_error('查無優惠活動資料');
}
$total_methods_count = $this->promote_method_model
->where('promote_id', $promote_id)
->count_rows();
$methods = $this->promote_method_model
->where('promote_id', $promote_id)
->order_by('sort')
->paginate(20, $total_methods_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_promote_method', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_promote_method', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_promote_method', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'promote_type' => $this->promote_type,
'promote' => $promote,
'methods' => $methods,
'pagination' => $this->promote_method_model->all_pages,
'authority' => $authority,
'title' => '優惠方式列表',
'view' => 'capital/promote/method/overview',
];
$this->_preload($data);
}
public function add($promote_id, $promote_type_id = '')
{
$promote = $this->promote_model
->with_items()
->with_relatives()
->get($promote_id);
if (!$promote_id || !$promote) {
show_error('查無優惠活動資料');
}
if ($promote_type_id && !empty($this->promote_type[$promote_type_id])) {
$products = $this->product_model->getCustomerProducts();
$combos = $this->combo_model->getAllCombos();
$options = null;
if ($promote_type_id == 3) {
$options['single'] = 0;
}
if ($this->input->post()) {
$this->form_validation->set_rules('discount_type', '優惠方式', 'required|alpha|in_list[F,P]');
if ($this->input->post('discount_type') == 'P') {
$this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
} else {
$this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[50]|less_than_equal_to[100000]');
}
if ($promote_type_id == 2) {
$this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[1000]|less_than_equal_to[100000]');
} elseif ($promote_type_id == 3) {
$this->form_validation->set_rules('single', '客戶只能擇一挑選贈品', 'integer');
$this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[0]');
}
if ($this->form_validation->run() !== FALSE) {
$next_sort = $this->promote_method_model->getNextSortOfPromoteMethod($promote_id);
if ($promote_type_id == 3) {
$options['single'] = (int)$this->input->post('single');
}
$promote_method_id = $this->promote_method_model->insert([
'promote_id' => $promote_id,
'promote_type_id' => $promote_type_id,
'discount_type' => $this->input->post('discount_type'),
'discount' => $this->input->post('discount'),
'limit' => empty($this->input->post('limit')) ? null : $this->input->post('limit'),
'options' => $options ? serialize($options) : null,
'sort' => $next_sort,
], ['id' => $promote_id]);
$items = (array)$this->input->post('items');
foreach ($items as $product_val) {
$tmp = explode('_', $product_val);
switch ($tmp[0]) {
case 'p':
$product_type = 'product';
break;
case 'c':
$product_type = 'combo';
break;
}
$product_id = $tmp[1];
$this->promote_item_model->insert([
'promote_method_id' => $promote_method_id,
'product_type' => $product_type,
'product_id' => $product_id,
]);
}
$relatives = (array)$this->input->post('relatives');
foreach ($relatives as $product_val) {
$tmp = explode('_', $product_val);
switch ($tmp[0]) {
case 'p':
$product_type = 'product';
break;
case 'c':
$product_type = 'combo';
break;
}
$product_id = $tmp[1];
$this->promote_item_relative_model->insert([
'promote_method_id' => $promote_method_id,
'product_type' => $product_type,
'product_id' => $product_id,
]);
}
redirect(base_url('/capital_promote_method/overview/' . $promote_id));
}
}
$data = [
'products' => $products,
'combos' => $combos,
'promote' => $promote,
'promote_type' => $this->promote_type[$promote_type_id],
'promote_method' => [],
'options' => $options,
'items' => [],
'relatives' => [],
'title' => '新增優惠方式',
'view' => 'capital/promote/method/advance' . $promote_type_id,
];
} else {
$data = [
'promote_type' => $this->promote_type,
'promote' => $promote,
'title' => '新增優惠方式',
'view' => 'capital/promote/method/add',
];
}
$this->load->helper('form');
$this->_preload($data);
}
public function edit($promote_method_id)
{
$promote_method = $this->promote_method_model
->with_promote()
->with_items()
->with_relatives()
->get($promote_method_id);
if (!$promote_method_id || !$promote_method) {
show_error('查無優惠方式資料');
}
$promote = $promote_method['promote'];
$products = $this->product_model->getCustomerProducts();
$combos = $this->combo_model->getAllCombos();
$options = null;
if ($promote_method['promote_type_id'] == 3) {
if ($promote_method['options']){
$options = unserialize($promote_method['options']);
}
}
if ($this->input->post()) {
$this->form_validation->set_rules('discount_type', '優惠方式', 'required|alpha|in_list[F,P]');
if ($this->input->post('discount_type') == 'P') {
$this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[1]|less_than_equal_to[100]');
} else {
$this->form_validation->set_rules('discount', '優惠值', 'required|integer|greater_than_equal_to[100]|less_than_equal_to[100000]');
}
if ($promote_method['promote_type_id'] == 2) {
$this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[1000]|less_than_equal_to[100000]');
} elseif ($promote_method['promote_type_id'] == 3) {
$this->form_validation->set_rules('single', '客戶只能擇一挑選贈品', 'integer');
$this->form_validation->set_rules('limit', '滿額值', 'required|integer|greater_than_equal_to[0]');
}
if ($this->form_validation->run() !== FALSE) {
if ($promote_method['promote_type_id'] == 3) {
$options['single'] = (int)$this->input->post('single');
}
$this->promote_method_model->update([
'discount_type' => $this->input->post('discount_type'),
'discount' => $this->input->post('discount'),
'limit' => empty($this->input->post('limit')) ? null : $this->input->post('limit'),
'options' => $options ? serialize($options) : null,
], ['id' => $promote_method_id]);
$this->promote_item_model->where('promote_method_id', $promote_method_id)->delete();
$this->promote_item_relative_model->where('promote_method_id', $promote_method_id)->delete();
$items = (array)$this->input->post('items');
if (!empty($items)) {
foreach ($items as $product_val) {
$tmp = explode('_', $product_val);
$product_type = '';
switch ($tmp[0]) {
case 'p':
$product_type = 'product';
break;
case 'c':
$product_type = 'combo';
break;
}
$product_id = $tmp[1];
if ($product_type && $product_id) {
$this->promote_item_model->insert([
'promote_method_id' => $promote_method_id,
'product_type' => $product_type,
'product_id' => $product_id,
]);
}
}
}
$relatives = (array)$this->input->post('relatives');
if (!empty($relatives)) {
foreach ($relatives as $product_val) {
$tmp = explode('_', $product_val);
$product_type = '';
switch ($tmp[0]) {
case 'p':
$product_type = 'product';
break;
case 'c':
$product_type = 'combo';
break;
}
$product_id = $tmp[1];
if ($product_type && $product_id) {
$this->promote_item_relative_model->insert([
'promote_method_id' => $promote_method_id,
'product_type' => $product_type,
'product_id' => $product_id,
]);
}
}
}
redirect(base_url('/capital_promote_method/overview/' . $promote['id']));
}
}
$_items = $promote_method['items'];
$items = [];
if ($_items) {
foreach ($_items as $item) {
if ($item['product_type'] == 'product') {
array_push($items, 'p_' . $item['product_id']);
} elseif ($item['product_type'] == 'combo') {
array_push($items, 'c_' . $item['product_id']);
}
}
}
$_relatives = $promote_method['relatives'];
$relatives = [];
if ($_relatives) {
foreach ($_relatives as $relative) {
if ($relative['product_type'] == 'product') {
array_push($relatives, 'p_' . $relative['product_id']);
} elseif ($relative['product_type'] == 'combo') {
array_push($relatives, 'c_' . $relative['product_id']);
}
}
}
$this->load->helper('form');
$data = [
'products' => $products,
'combos' => $combos,
'promote' => $promote,
'promote_method' => $promote_method,
'options' => $options,
'items' => $items,
'relatives' => $relatives,
'title' => '編輯優惠方式',
'view' => 'capital/promote/method/advance' . $promote_method['promote_type_id'],
];
$this->_preload($data);
}
public function cancel($promote_method_id)
{
$promote_method = $this->promote_method_model
->get($promote_method_id);
if (!$promote_method_id || !$promote_method) {
show_error('查無優惠方式資料');
}
$promote_id = $promote_method['promote_id'];
$this->promote_method_model->delete($promote_method_id);
redirect(base_url('/capital_promote_method/overview/' . $promote_id));
}
}
?><file_sep>/application/models/Retailer_level_type_model.php
<?php
class Retailer_level_type_model extends MY_Model
{
public $table = 'olive_retailer_level_types';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['levels'] = array('Retailer_level_model', 'retailer_level_type_id', 'id');
}
public function getTypeSelect()
{
$_types = $this->get_all();
$types = [];
foreach ($_types as $type){
$types[$type['id']] = $type['title'];
}
return $types;
}
}
?>
<file_sep>/application/migrations/012_add_purchase.php
<?php
//經銷商訂貨單
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_purchase extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'retailer_address' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'shipin_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'shipin_address' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'shipout_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'invoice_retailer' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'invoice_send_retailer' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => TRUE,
],
'invoice_send_address' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'serialNum' => [
'type' => 'VARCHAR',
'constraint' => 5,
],
'purchaseNum' => [
'type' => 'VARCHAR',
'constraint' => 11,
],
'totalQty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'subtotal' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'total' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'fare' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'isInvoice' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'isConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'isPaid' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'paid_at' => [
'type' => 'date',
'null' => TRUE,
],
'isShipped' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'shipped_at' => [
'type' => 'date',
'null' => TRUE,
],
'isShortage' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'isDefect' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'isReturn' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'importMethod' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_purchases');
}
public function down()
{
$this->dbforge->drop_table('olive_purchases');
}
}<file_sep>/application/views/capital/pao/overview.php
<div class="container">
<h1 class="mb-4">商品期限參數設定
<?php if (!empty($authority['add'])){ ?>
<a href="<?= base_url('/capital_pao/add') ?>" class="btn btn-success float-right"><i class="far fa-plus-square"></i> 新增商品期限參數</a>
<?php } ?>
</h1>
<table class="table table-hover table-bordered">
<tr>
<th>有效期限</th>
<th>PAO</th>
<th></th>
</tr>
<?php
if ($paos) {
foreach ($paos as $pao) {
?>
<tr>
<td><?= $pao['expiration_month'] ?>月</td>
<td><?= $pao['pao_month'] ?>月</td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['edit'])){ ?>
<a class="btn btn-warning btn-sm" href="<?= base_url('/capital_pao/edit/' . $pao['id']) ?>">編輯</a>
<?php } ?>
<button type="button" class="btn btn-warning btn-sm dropdown-toggle dropdown-toggle-split" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<?php if (!empty($authority['cancel'])){ ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#"
data-href="<?= base_url('/capital_pao/cancel/' . $pao['id']) ?>"
data-toggle="modal" data-target="#confirm-delete"><i class="fas fa-trash"></i> 刪除</a>
<?php } ?>
</div>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="3" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal" id="confirm-delete" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-trash"></i> 刪除確認</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>是否確定刪除?</p>
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="btn" data-dismiss="modal"><i class="fas fa-ban"></i> 取消</button>
<a href="" class="btn btn-danger btn-confirm"><i class="fas fa-trash"></i> 刪除</a>
</div>
</div>
</div>
</div>
<script>
$().ready(function(){
$('#confirm-delete').on('show.bs.modal', function(e){
$(this).find('.btn-confirm').attr('href', $(e.relatedTarget).data('href'));
});
});
</script><file_sep>/application/controllers/Payment.php
<?php
class Payment extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
$this->load->model('shipment_model');
$this->load->model('purchase_model');
$this->load->model('payment_model');
$this->load->library('purchase_lib');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/purchase/overview'));
}
public function overview()
{
$total_payments_count = $this->payment_model
->where('paid_retailer_id', $this->dealer['retailer_id'])
->where('pay_type', '!=', 'order')
->count_rows();
$payments = $this->payment_model
->with_paid_retailer('fields:company')
->with_received_retailer('fields:company')
->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
->where('paid_retailer_id', $this->dealer['retailer_id'])
->where('pay_type', '!=', 'order')
->order_by('active', 'asc')
->order_by('id', 'desc')
->paginate(20, $total_payments_count);
if ($payments){
foreach ($payments as $key => $payment){
$payments[$key]['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('confirm', 'overview')){
$authority['confirm'] = true;
}
if ($this->authentic->authority('payment', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'payments' => $payments,
'pagination' => $this->payment_model->all_pages,
'authority' => $authority,
'title' => '付款紀錄列表',
'view' => 'payment/overview',
];
$this->_preload($data);
}
public function purchase($purchase_id)
{
$purchase = $this->purchase_model
->where('retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase_id || !$purchase) {
show_error('查無進貨單資料');
}
$payment = $this->payment_model
->where('pay_type', 'purchase')
->where('pay_id', $purchase_id)
->where('paid_retailer_id', $this->dealer['retailer_id'])
->where('active', 0)
->get();
if ($payment){
redirect(base_url('/payment/add/' . $payment['id']));
} else {
redirect(base_url('/payment/overview'));
}
}
public function add($payment_id)
{
$payment = $this->payment_model
->with_paid_retailer('fields:company')
->with_received_retailer()
->where('paid_retailer_id', $this->dealer['retailer_id'])
->where('active', 0)
->where('pay_type', '!=', 'order')
->get($payment_id);
if (!$payment_id || !$payment) {
show_error('查無付款資料');
}
switch ($payment['pay_type']){
case 'purchase':
$purchase = $this->purchase_model
->with_transfer_from()
->get($payment['pay_id']);
if (!$purchase['isConfirmed']) {
show_error('進貨單尚未確認');
} elseif ($purchase['isPaid']){
show_error('進貨單已經付款');
} elseif (!empty($purchase['transfer_from']) && (!$purchase['transfer_from']['isPaid'] || !$purchase['transfer_from']['isPayConfirmed'])){
show_error('原轉單進貨單尚未付款');
}
break;
case 'shipment_allowance':
$purchase = $this->purchase_model
->get($payment['pay_id']);
if (!$purchase){
show_error('查無進貨單資料');
}
break;
}
$error = [];
if ($this->input->post()) {
$this->form_validation->set_rules('type_id', '付款方式', 'required|integer|in_list[' . implode(',', array_keys(paymentType())) . ']');
if ($this->form_validation->run() !== FALSE) {
if ($this->input->post('type_id') == 2) { //匯款
if (empty($_FILES)) {
$error[] = '請上傳付款憑證';
} else {
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$receipt = null;
if ($_FILES['receipt'] && $_FILES['receipt']['size']) {
if ($this->upload->do_upload('receipt')) {
$upload_data = $this->upload->data();
$receipt = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
} else {
$error[] = '請上傳付款憑證';
}
}
}
if (!$error) {
$this->payment_model->update([
'type_id' => $this->input->post('type_id'),
'receipt' => $receipt,
'active' => 1,
'isConfirmed' => null,
], ['id' => $payment_id]);
switch ($payment['pay_type']) {
case 'purchase':
$unpaid_count = $this->payment_model
->where('pay_type', 'purchase')
->where('pay_id', $payment['pay_id'])
->where('active', 0)
->count_rows();
if (!$unpaid_count) {
$this->purchase_model->update(['isPaid' => 1, 'paid_at' => date('Y-m-d H:i:s')], ['id' => $payment['pay_id']]);
}
redirect(base_url('/purchase/detail/' . $payment['pay_id']));
break;
case 'shipment_allowance':
redirect(base_url('/transfer/detail/' . $payment['pay_id']));
break;
}
}
}
}
$data = [
'error' => $error,
'payment' => $payment,
'title' => '新增付款紀錄',
'view' => 'payment/add',
];
$this->_preload($data);
}
public function confirms()
{
$total_payments_count = $this->payment_model
->where('received_retailer_id', $this->dealer['retailer_id'])
->where('pay_type', '!=', 'order')
->count_rows();
$payments = $this->payment_model
->with_paid_retailer('fields:company')
->with_received_retailer('fields:company')
->with_confirm(['non_exclusive_where' => "confirm_type='payment'"])
->where('received_retailer_id', $this->dealer['retailer_id'])
->where('active', 1)
->where('pay_type', '!=', 'order')
->order_by('isConfirmed', 'asc')
->order_by('id', 'desc')
->paginate(20, $total_payments_count);
if ($payments){
foreach ($payments as $key => $payment){
$payments[$key]['payment_confirm_label'] = $this->payment_model->generatePaymentConfirmLabel($payment, true);
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('payment', 'confirm')){
$authority['confirm'] = true;
}
$data = [
'payments' => $payments,
'pagination' => $this->payment_model->all_pages,
'authority' => $authority,
'title' => '待確認收款列表',
'view' => 'payment/confirms',
];
$this->_preload($data);
}
public function confirm($payment_id)
{
$payment = $this->payment_model
->with_paid_retailer('fields:company')
->with_received_retailer('fields:company')
->where('received_retailer_id', $this->dealer['retailer_id'])
->where('active', 1)
->where('pay_type', '!=', 'order')
->get($payment_id);
if (!$payment_id || !$payment) {
show_error('查無付款資料');
}
if (!is_null($payment['isConfirmed'])){
show_error('已確認過付款資料');
}
if ($this->input->post()) {
$audit = 0;
if (isset($_POST['confirmed'])) {
$audit = 1;
}
$this->load->model('confirm_model');
$this->confirm_model->insert([
'confirm_type' => 'payment',
'confirm_id' => $payment_id,
'audit_retailer_id' => $this->dealer['retailer_id'],
'audit' => $audit,
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'dealer_id' => $this->dealer['id'],
]);
$this->payment_model->update(['active' => $audit, 'isConfirmed' => $audit], ['id' => $payment_id]);
switch ($payment['pay_type']) {
case 'purchase':
if (!$audit) {
$this->purchase_model->update(['isPaid' => 0, 'paid_at' => null], ['id' => $payment['pay_id']]);
} else {
$this->purchase_model->update(['isPayConfirmed' => 1], ['id' => $payment['pay_id']]);
$this->purchase_model->checkCorrect($payment['pay_id']);
}
redirect(base_url('/transfer/detail/' . $payment['pay_id']));
break;
case 'shipment_allowance':
if ($audit) {
$this->purchase_model->checkHasAllowance($payment['pay_id']);
$this->purchase_model->checkCorrect($payment['pay_id']);
}
redirect(base_url('/purchase/detail/' . $payment['pay_id']));
break;
}
}
$data = [
'payment' => $payment,
'title' => '確認付款',
'view' => 'payment/confirm',
];
$this->_preload($data);
}
public function cancel($payment_id)
{
$payment = $this->payment_model
->where('pay_type', '!=', 'order')
->get($payment_id);
if (!$payment_id || !$payment) {
show_error('查無付款資料');
}
if (!is_null($payment['isConfirmed'])){
show_error('付款已經確認不能取消');
}
switch ($payment['pay_type']) {
case 'purchase':
$purchase = $this->purchase_model
->get($payment['pay_id']);
if (!$purchase) {
show_error('查無進貨單資料');
}
$this->purchase_model->update(['isPaid' => 0, 'paid_at' => null],['id' => $payment['pay_id']]);
break;
case 'shipment_allowance':
$purchase = $this->purchase_model
->get($payment['pay_id']);
if (!$purchase) {
show_error('查無進貨單資料');
}
break;
}
$this->payment_model->delete($payment_id);
redirect(base_url('/payment/overview'));
}
}
?><file_sep>/application/views/capital/relationship/visor/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增輔銷關係單位</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>輔銷單位</label>
<?php
echo form_dropdown('retailer_id', ['' => ''] + $retailer_selects, set_value('retailer_id'), 'class="form-control required"');
?>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_relationship_visor/overview/' . $retailer['id'])?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/coupon/detail.php
<div class="container">
<h1 class="mb-4"><?= date('Y年m月', strtotime($coupon['coupon_month'])) ?> 核發記錄明細</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">項次</th>
<th class="text-center">折價券編號</th>
<th class="text-center">消費編號</th>
</tr>
<?php
if ($coupon['approves']) {
$i = 1;
foreach ($coupon['approves'] as $approve) {
?>
<tr>
<td class="text-center">#<?= $i ?></td>
<td class="text-center"><?= $approve['couponNum'] ?></td>
<td class="text-center"><?= $approve['order']['orderNum'] ?></td>
<?php
$i++;
}
}
?>
</table>
</div><file_sep>/application/views/capital/product/permission/overview.php
<div class="container">
<h1 class="mb-4">進貨商品管理</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號</th>
<th>貨品名稱</th>
<th>單價</th>
<th>可進貨單位</th>
<th>備註</th>
<th></th>
</tr>
<?php
if ($products) {
$i = 1;
foreach ($products as $product) {
?>
<tr>
<td class="text-center"><?= $i ?></td>
<td><?= $product['p_num'] ?></td>
<td>
<?= $product['pdName'] ?> <?= $product['intro2'] ?>
</td>
<td class="item_cash text-right">$<?= number_format($product['pdCash']) ?></td>
<td><?= empty($permissions[$product['pdId']]['retailers']) ? '全部' : implode(', ', $permissions[$product['pdId']]['retailers'])?></td>
<td><?= empty($permissions[$product['pdId']]['remark']) ? '' : $permissions[$product['pdId']]['remark']?></td>
<td>
<div class="btn-group" role="group">
<?php if (!empty($authority['edit'])){ ?>
<a class="btn btn-warning btn-sm" href="<?= base_url('/capital_product_permission/edit/' . $product['pdId']) ?>">編輯</a>
<?php } ?>
</div>
</td>
</tr>
<?php
$i++;
}
} else {
?>
<tr>
<td colspan="7" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
</div><file_sep>/application/migrations/068_update_retailer_active.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_active extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_retailers', [
'disabled_at' => [
'type' => 'timestamp',
'null' => TRUE,
'after' => 'isAllowBulk',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_retailers', 'disabled_at');
}
}<file_sep>/application/migrations/066_update_retailer_level_code.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_level_code extends CI_Migration {
public function up()
{
$this->dbforge->modify_column('olive_retailer_levels', [
'code' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
]);
}
public function down()
{
$this->dbforge->modify_column('olive_retailer_levels', [
'code' => [
'type' => 'CHAR',
'constraint' => 1,
'null' => TRUE,
],
]);
}
}<file_sep>/application/views/consumer/transfer_delivery.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">A店買B店取貨之確認取貨</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">收貨人</label>
<div><?= !empty($transfer['order']['contact']['name']) ? $transfer['order']['contact']['name'] : '' ?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">連絡電話</label>
<div><?= !empty($transfer['order']['contact']['phone']) ? $transfer['order']['contact']['phone'] : '' ?></div>
</div>
<h4 class="my-4 text-center">貨品內容</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>貨品名稱</td>
<td>訂購數量</td>
<td>庫存到期日</td>
<td>庫存數量</td>
<td>出貨數量</td>
</tr>
<?php
if ($products) {
foreach ($products as $product_id => $product) {
$stock_row = count($product['stocks']);
?>
<tr>
<td rowspan="<?=$stock_row?>" class="align-middle"><?= $product['name'] ?></td>
<td rowspan="<?=$stock_row?>" class="align-middle text-right"><?= $product['qty'] ?></td>
<?php if (empty($product['stocks'][0])){ ?>
<td class="align-middle"></td>
<td class="align-middle">無庫存</td>
<td class="align-middle"></td>
<?php
} else {
$qty = min($product['qty'], $product['stocks'][0]['stock']);
?>
<td class="align-middle">
<?= $product['stocks'][0]['expired_at'] ? $product['stocks'][0]['expired_at'] : '未標示'?>
</td>
<td class="align-middle text-right"><?= number_format($product['stocks'][0]['stock']) ?></td>
<td class="align-middle">
<input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$product['stocks'][0]['expired_at']?>]" max="<?=$product['stocks'][0]['stock']?>" min="0" value="<?=$qty?>" />
</td>
<?php
if ($product['qty'] == $qty){
$product['qty'] = 0;
} else {
$product['qty'] -= $product['stocks'][0]['stock'];
}
}
?>
</tr>
<?php
if ($stock_row > 1){
foreach ($product['stocks'] as $k => $stock) {
if ($k > 0) {
$qty = min($product['qty'], $product['stocks'][0]['stock']);
?>
<tr>
<td class="align-middle"><?= $stock['expired_at'] ? $stock['expired_at'] : '未標示' ?></td>
<td class="align-middle text-right"><?= number_format($stock['stock']) ?></td>
<td class="align-middle">
<input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$stock['expired_at']?>]" max="<?=$stock['stock']?>" min="0" value="<?=$qty?>" />
</td>
</tr>
<?php
if ($product['qty'] == $qty){
$product['qty'] = 0;
} else {
$product['qty'] -= $product['stocks'][0]['stock'];
}
}
}
}
?>
<?php
}
}
?>
</table>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/consumer/transfer')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="確認取貨"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/capital/retailer/role/overview.php
<div class="container">
<h1 class="mb-4">單位類型列表</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">名稱</th>
<th></th>
</tr>
<?php
if ($roles) {
foreach ($roles as $role) {
if (!empty($role['level_types'])){
foreach ($role['level_types'] as $level_type){
?>
<tr>
<td class="text-center"><?= $level_type['title'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<a class="btn btn-info btn-sm"
href="<?= base_url('/capital_retailer_group/overview/' . $role['id'] . '_' . $level_type['id']) ?>">群組列表</a>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td class="text-center"><?= $role['title'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<a class="btn btn-info btn-sm"
href="<?= base_url('/capital_retailer_group/overview/' . $role['id']) ?>">群組列表</a>
</div>
</td>
</tr>
<?php
}
}
}
?>
</table>
</div><file_sep>/application/views/coupon/approved.php
<div class="container">
<h1 class="mb-4">審核折價券</h1>
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">單位名稱</th>
<td class="text-center"><?= $confirm['coupon']['retailer']['company'] ?></td>
</tr>
<tr>
<th class="text-center">年分/月份</th>
<td class="text-center"><?= date('Y年m月', strtotime($confirm['coupon']['coupon_month'])) ?></td>
</tr>
<tr>
<th class="text-center">領用張數</th>
<td class="text-center"><?= $confirm['coupon']['receive_qty'] ?></td>
</tr>
</table>
<form method="post">
<div class="form-group text-center">
<input type="submit" name="refused" class="btn btn-danger" value="拒絕"/>
<input type="submit" name="approved" class="btn btn-success" value="確認"/>
</div>
</form>
</div><file_sep>/application/models/Country_model.php
<?php
class Country_model extends MY_Model{
public $table = 'country';
public $primary_key = 'cyId';
function __construct(){
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
}
}
?>
<file_sep>/application/views/transfer/overview.php
<div class="container">
<h1 class="mb-4"><?= $dealer['company'] ?> 出貨單列表</h1>
<div>
<p>1. 訂貨通知=送出進貨單之日期=新增進貨單</p>
<p>2. 進貨日期=出貨日期=收貨日期=新增出貨通知之日期(因為必須同時寄出商品方能新增出貨通知)</p>
</div>
<form id="search_form">
<div class="card mb-4">
<div class="card-header">搜尋</div>
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-3">
<label for="purchaseNum">出貨單編號</label>
<input class="form-control" name="purchaseNum" value="<?=$search['purchaseNum']?>" />
</div>
<div class="form-group col-md-3">
<label for="shipin_retailer_id">進貨單位</label>
<select name="shipin_retailer_id" class="form-control" required>
<option>全部</option>
<?php foreach ($shipin_retailers as $retailer){ ?>
<option value="<?=$retailer['id']?>"<?php if ($search['shipin_retailer_id'] == $retailer['id']){ echo 'selected'; } ?>><?=$retailer['company']?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-md-3">
<label for="created_start">訂貨日期起</label>
<input type="date" class="form-control" name="created_start" value="<?=$search['created_start']?>" />
</div>
<div class="form-group col-md-3">
<label for="created_end">訂貨日期訖</label>
<input type="date" class="form-control" name="created_end" value="<?=$search['created_end']?>" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="isConfirmed">回覆進貨單位</label>
<select name="isConfirmed" class="form-control">
<option value=""<?php if ($search['isConfirmed'] === ''){ echo 'selected';}?>>全部</option>
<option value="-1"<?php if ($search['isConfirmed'] === '-1'){ echo 'selected';}?>>待回覆</option>
<option value="1"<?php if ($search['isConfirmed'] === '1'){ echo 'selected';}?>>同意</option>
<option value="0"<?php if ($search['isConfirmed'] === '0'){ echo 'selected';}?>>拒絕</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="isDeleted">進貨單位取消進貨</label>
<select name="isDeleted" class="form-control">
<option value=""<?php if ($search['isDeleted'] === ''){ echo 'selected';}?>>全部</option>
<option value="1"<?php if ($search['isDeleted'] === '1'){ echo 'selected';}?>>是</option>
<option value="0"<?php if ($search['isDeleted'] === '0'){ echo 'selected';}?>>否</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="isPaid">收款狀態</label>
<select name="isPaid" class="form-control">
<option value=""<?php if ($search['isPaid'] === ''){ echo 'selected';}?>>全部</option>
<option value="1"<?php if ($search['isPaid'] === '1'){ echo 'selected';}?>>是</option>
<option value="0"<?php if ($search['isPaid'] === '0'){ echo 'selected';}?>>否</option>
</select>
</div>
<div class="form-group col-md-3">
<label for="isShipped">出貨決定</label>
<select name="isShipped" class="form-control">
<option value=""<?php if ($search['isShipped'] === ''){ echo 'selected';}?>>全部</option>
<option value="1"<?php if ($search['isShipped'] === '1'){ echo 'selected';}?>>是</option>
<option value="0"<?php if ($search['isShipped'] === '0'){ echo 'selected';}?>>否</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<label for="isReceived">收貨狀態</label>
<select name="isReceived" class="form-control">
<option value=""<?php if ($search['isShipped'] === ''){ echo 'selected';}?>>全部</option>
<option value="isCorrect"<?php if ($search['isReceived'] === 'isCorrect'){ echo 'selected';}?>>收貨無誤</option>
<option value="isRevised"<?php if ($search['isReceived'] === 'isRevised'){ echo 'selected';}?>>銷貨異動</option>
<option value="isReturn"<?php if ($search['isReceived'] === 'isReturn'){ echo 'selected';}?>>銷貨退回</option>
<option value="isAllowance"<?php if ($search['isReceived'] === 'isAllowance'){ echo 'selected';}?>>銷貨折讓</option>
</select>
</div>
</div>
</div>
<div class="card-footer text-center">
<input type="submit" value="搜尋" class="btn btn-primary" />
<a href="<?=base_url('/transfer/overview')?>" class="btn btn-light">重設</a>
</div>
</div>
</form>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">出貨單編號</th>
<th class="text-center">訂貨日期</th>
<th class="text-center">出貨單位</th>
<th class="text-center">進貨單位</th>
<th class="text-center">回覆進貨單位</th>
<th class="text-center">進貨單位取消進貨</th>
<th class="text-center">收款狀態</th>
<th class="text-center">出貨決定</th>
<th class="text-center">收貨狀態</th>
<th class="text-center">出貨日期</th>
<th class="text-center"></th>
</tr>
<?php
if ($purchases) {
foreach ($purchases as $purchase) {
?>
<tr <?php if (!is_null($purchase['deleted_at']) || $purchase['isConfirmed'] === '0'){ ?>class="table-danger"<?php } elseif (!is_null($purchase['transfer_id'])) { ?>class="table-info"<?php } ?>>
<td class="text-center">
<?= $purchase['purchaseNum'] ?>
<?php if (!is_null($purchase['transfer_id'])){ ?>
<a class="btn btn-info btn-sm" href="<?=base_url('/purchase/overview?purchaseNum=' . $purchase['transfer_to']['purchaseNum'])?>">轉單已成立</a>
<?php } ?>
</td>
<td class="text-center"><?= $purchase['created_at'] ?></td>
<td class="text-center"><?= empty($purchase['shipout_retailer']) ? '' : $purchase['shipout_retailer']['company'] ?></td>
<td class="text-center"><?= $purchase['retailer']['company'] ?></td>
<td class="text-center"><?= $purchase['confirm_label'] ?></td>
<td class="text-center"><?= yesno(!is_null($purchase['deleted_at'])) ?></td>
<td class="text-center"><?= $purchase['paid_label'] ?></td>
<td class="text-center"><?= $purchase['shipped_label']?></td>
<td class="text-center">
<?php
if ($purchase['isShipped']) {
if ($purchase['isRevised']) echo '<span class="badge badge-danger mr-1">銷貨異動</span>';
if ($purchase['isReturn']) echo '<span class="badge badge-danger mr-1">銷貨退回</span>';
if ($purchase['isAllowance']) echo '<span class="badge badge-danger mr-1">銷貨折讓</span>';
if ($purchase['isShipConfirmed'] && !$purchase['isRevised'] && !$purchase['isReturn'] && !$purchase['isAllowance']) echo '<span class="badge badge-dark">收款無誤/結案</span>';
}
?>
</td>
<td class="text-center"><?= $purchase['shipped_at'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php
if (!empty($authority['transfer']) && empty($purchase['order_transfer']) && is_null($purchase['transfer_id']) && is_null($purchase['isConfirmed'])) {
if ($purchase['shipout_retailer_id'] != 1){
?>
<a class="btn btn-warning btn-sm"
href="<?= base_url('/transfer/transfer/' . $purchase['id']) ?>">
轉單
</a>
<?php
}
}
?>
<?php
if (!empty($authority['confirm']) && empty($purchase['order_transfer']) && is_null($purchase['isConfirmed'])) {
if ($purchase['shipout_retailer_id'] == $dealer['retailer_id']) {
?>
<form class="confirm_tranfer" method="post" action="<?= base_url('/transfer/confirm/' . $purchase['id']) ?>">
<input type="submit" name="confirmed" class="btn btn-primary btn-sm" value="確認出貨單"/>
</form>
<a class="btn btn-danger btn-sm" href="#"
data-href="<?= base_url('/transfer/confirm/' . $purchase['id']) ?>"
data-toggle="modal" data-target="#confirm-reject">拒絕出貨單</a>
<?php
}
}
?>
<?php
if (!empty($authority['payment_confirm']) && $purchase['isPaid'] && !$purchase['isPayConfirmed']) {
foreach ( array_reverse($purchase['payments']) as $payment) {
if ($payment['active'] == 1 && $payment['received_retailer_id'] == $dealer['retailer_id']){
if (is_null($payment['isConfirmed'])) {
?>
<a class="btn btn-primary btn-sm"
href="<?= base_url('/payment/confirm/' . $payment['id']) ?>">
收款作業
</a>
<?php
}
break;
}
}
}
?>
<?php if (!empty($authority['shipment_add']) && empty($purchase['order_transfer']) && (empty($purchase['transfer_to']) || (!empty($purchase['transfer_to']['transfer_to']) && $purchase['transfer_to']['transfer_to']['isShipConfirmed'])) && $purchase['isConfirmed'] && $purchase['isPaid'] && !$purchase['isShipped']) { ?>
<a class="btn btn-warning btn-sm"
href="<?= base_url('/shipment/add/' . $purchase['id']) ?>">
<i class="far fa-bell"></i> 出貨通知
</a>
<?php } ?>
<?php if (!empty($authority['detail'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/transfer/detail/' . $purchase['id']) ?>">
詳細
</a>
<?php } ?>
<?php if (!empty($authority['detail2'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/transfer/detail2/' . $purchase['id']) ?>">
詳細
</a>
<?php } ?>
<?php if (!empty($authority['shipment_detail']) && $purchase['isShipped']) { ?>
<button type="button" class="btn btn-info btn-sm dropdown-toggle dropdown-toggle-split"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="<?= base_url('/shipment/detail/' . $purchase['id']) ?>">
出貨紀錄列表
</a>
</div>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="11" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal" id="confirm-reject" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">拒絕出貨單</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>是否已通知進貨單位取消訂單?</p>
</div>
<div class="modal-footer d-flex justify-content-between">
<button type="button" class="btn" data-dismiss="modal">否</button>
<form class="confirm_tranfer" method="post">
<input type="submit" name="rejected" class="btn btn-danger btn-sm" value="是"/>
</form>
</div>
</div>
</div>
</div>
<script>
$().ready(function () {
$('#confirm-reject').on('show.bs.modal', function (e) {
$(this).find('.confirm_tranfer').attr('action', $(e.relatedTarget).data('href'));
});
});
</script><file_sep>/application/models/Customer_level_history_model.php
<?php
class Customer_level_history_model extends MY_Model
{
public $table = 'olive_customer_level_histories';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['customer'] = array('foreign_model' => 'Customer_model', 'foreign_table' => 'olive_customers', 'foreign_key' => 'id', 'local_key' => 'customer_id');
$this->has_one['old_level'] = array('foreign_model' => 'Customer_level_model', 'foreign_table' => 'olive_customer_levels', 'foreign_key' => 'id', 'local_key' => 'old_customer_level_id');
$this->has_one['new_level'] = array('foreign_model' => 'Customer_level_model', 'foreign_table' => 'olive_customer_levels', 'foreign_key' => 'id', 'local_key' => 'new_customer_level_id');
}
}
?>
<file_sep>/application/views/capital/privilege/apps.php
<div class="container">
<h1 class="mb-4"><?= $class_list[$classname]['alias'] ?> 動作總覽</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<thead>
<tr>
<th class="text-left">動作名稱</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if ($class_list[$classname]['method']) {
foreach ($class_list[$classname]['method'] as $methodname => $title) {
?>
<tr>
<td class="text-left"><?= $title ?></td>
<td class="text-center">
<div class="btn-group">
<?php if (!empty($authority['authority'])){ ?>
<a class="btn btn-info"
href="<?= base_url('/capital_privilege/authority/' . $classname . '/' . $methodname) ?>">設定權限</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="2" class="text-center">查無資料</td>
</tr>
<?php } ?>
</tbody>
</table>
</div><file_sep>/application/models/Product_model.php
<?php
class Product_model extends MY_Model
{
public $table = 'product';
public $primary_key = 'pdId';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
$this->has_one['product_kind'] = array('foreign_model'=>'Product_kind_model','foreign_table'=>'product_kind','foreign_key'=>'ctId','local_key'=>'pKind');
$this->has_one['pao'] = array('foreign_model'=>'Pao_model','foreign_table'=>'olive_paos','foreign_key'=>'id','local_key'=>'pao_id');
$this->has_many['stocks'] = array('Stock_model', 'product_id', 'pdId');
$this->has_many['permissions'] = array('Product_permission_model', 'product_id', 'pdId');
}
public function getProducts()
{
$_products = $this
->with_product_kind('fields:ctName')
->with_pao()
->where('boxAmount', '>', 0)
->where('pKind', [3,6])
->where('pEnable', 'Y')
->order_by('pKind', 'asc')
->order_by('sort_order', 'asc')
->get_all();
$products = [];
foreach ($_products as $p) {
$p['qty'] = '';
$products[$p['pdId']] = $p;
}
return $products;
}
public function getPermissionProducts($retailer_id)
{
$_products = $this
->with_product_kind('fields:ctName')
->with_pao()
->with_permissions(['non_exclusive_where' => "FIND_IN_SET(" . $retailer_id . ",include_retaifflers) AND include_retailers IS NULL"])
->where('pKind', [3,6])
->where('pEnable', 'Y')
->order_by('pKind', 'asc')
->order_by('sort_order', 'asc')
->get_all();
$products = [];
foreach ($_products as $p) {
$p['qty'] = '';
$products[$p['pdId']] = $p;
}
return $products;
}
public function getCustomerProducts()
{
$_products = $this
->with_product_kind('fields:ctName')
->with_pao()
->where('pKind', [3,6])
->where('pEnable', 'Y')
->order_by('pKind', 'asc')
->order_by('sort_order', 'asc')
->get_all();
$products = [];
foreach ($_products as $p) {
$p['qty'] = '';
$products[$p['pdId']] = $p;
}
return $products;
}
public function getPackageProducts()
{
$_products = $this
->with_product_kind('fields:ctName')
->with_pao()
->where('pKind', 6)
->where('pEnable', 'Y')
->order_by('pKind', 'asc')
->order_by('sort_order', 'asc')
->get_all();
$products = [];
foreach ($_products as $p) {
$p['qty'] = '';
$products[$p['pdId']] = $p;
}
return $products;
}
public function getUnitProductStocks($retailer_id)
{
$_products = $this
->with_pao()
->where('pKind', [3,6])
->where('pEnable', 'Y')
->order_by('pKind', 'asc')
->order_by('sort_order', 'asc')
->get_all();
$products = [];
$this->load->model('stock_model');
foreach ($_products as $p) {
$stocks = $this->stock_model
->where('product_id', $p['pdId'])
->where('retailer_id', $retailer_id)
->where('stock', '>', 0)
->order_by('expired_at', 'asc')
->get_all();
$p['stocks'] = $stocks;
$p['stock'] = $this->calcStock($stocks, $p);
$products[$p['pdId']] = $p;
}
return $products;
}
public function calcStock($stocks, $p)
{
$pao_month = 0;
if (!is_null($p['pao_id'])) {
$pao_month = $p['pao']['pao_month'];
}
$stock = [
'normal' => [
'total' => 0,
'data' => [],
],
'nearing' => [
'total' => 0,
'data' => [],
],
'expired' => [
'total' => 0,
'data' => [],
],
'untag' => [
'total' => 0,
],
'total' => 0,
'active_total' => 0,
];
if (!empty($stocks)){
foreach ($stocks as $s){
if ($s['stock'] > 0) {
if (is_null($s['expired_at'])) {
$stock['untag']['total'] += $s['stock'];
$stock['active_total'] += $s['stock'];
} else {
$expired_timestamp = strtotime($s['expired_at']);
$today = strtotime(date('Y-m-d'));
if ($pao_month) {
$pao_timestamp = strtotime("-" . $pao_month . " months", $expired_timestamp);
} else {
$pao_timestamp = $expired_timestamp;
}
if ($today <= $pao_timestamp) {
$stock['normal']['total'] += $s['stock'];
$stock['active_total'] += $s['stock'];
$stock['normal']['data'][] = $s;
} elseif ($today > $pao_timestamp && $today <= $expired_timestamp) {
$stock['active_total'] += $s['stock'];
$stock['nearing']['total'] += $s['stock'];
$stock['nearing']['data'][] = $s;
} elseif ($today > $expired_timestamp) {
$stock['expired']['total'] += $s['stock'];
$stock['expired']['data'][] = $s;
}
}
$stock['total'] += $s['stock'];
}
}
}
return $stock;
}
}
?>
<file_sep>/application/models/Customer_model.php
<?php
class Customer_model extends MY_Model
{
public $table = 'olive_customers';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['old'] = array('foreign_model' => 'Old_customer_model', 'foreign_table' => 'olive_old_customers', 'foreign_key' => 'id', 'local_key' => 'old_customer_id');
$this->has_one['level'] = array('foreign_model' => 'Customer_level_model', 'foreign_table' => 'olive_customer_levels', 'foreign_key' => 'id', 'local_key' => 'customer_level_id');
}
}
?>
<file_sep>/application/models/Promote_method_model.php
<?php
class Promote_method_model extends MY_Model
{
public $table = 'olive_promote_methods';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['promote'] = array('foreign_model' => 'Promote_model', 'foreign_table' => 'olive_promotes', 'foreign_key' => 'id', 'local_key' => 'promote_id');
$this->has_many['items'] = array('Promote_item_model', 'promote_method_id', 'id');
$this->has_many['relatives'] = array('Promote_item_relative_model', 'promote_method_id', 'id');
}
public function getNextSortOfPromoteMethod($promote_id)
{
$method = $this
->where('promote_id', $promote_id)
->order_by('sort', 'desc')
->get();
if ($method) {
return (int)$method['sort'] + 1;
} else {
return 1;
}
}
}
?>
<file_sep>/application/views/stock_counting/detail.php
<div class="container">
<div class="float-right">
<p>盤點日期: <?= date('Y/m/d', strtotime($stock_counting['created_at'])) ?></p>
<p>盤點編號: <?= $stock_counting['countingNum'] ?></p>
<p>盤點事由: <?= $counting_reason[$stock_counting['counting_reason']] ?></p>
</div>
<h1 class="mb-4"><?= $dealer['company'] ?>盤盈虧報表</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">項次</th>
<th class="text-center">貨品編號</th>
<th class="text-center">貨品名稱</th>
<th class="text-center">庫存</th>
<th class="text-center">到期日</th>
<th class="text-center">盤點量</th>
<th class="text-center">盤點盈虧</th>
<th class="text-center">盤差說明</th>
<th class="text-center">附件</th>
</tr>
<?php
if ($stock_counting['items']) {
$i = 1;
foreach ($stock_counting['items'] as $item) {
?>
<tr<?= ($item['product']['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center"><?= $i ?></td>
<td class="text-center"><?= $item['product']['p_num'] ?></td>
<td class="text-center"><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td class="text-right"><?= $item['old_stock'] ?></td>
<td class="text-right"><?= $item['expired_at'] ?></td>
<td class="text-right"><?= $item['stock'] ?></td>
<td class="text-right"><?= ($item['stock'] - $item['old_stock']) ?></td>
<td class="text-right"><?= $item['diff_reason'] ?></td>
<td class="text-center">
<?php if (!is_null($item['diff_file'])){ ?>
<a href="<?=$item['diff_file']?>" target="_blank" class="btn btn-info">附件</a>
<?php } ?>
</td>
</tr>
<?php
$i++;
}
}
?>
</table>
</div><file_sep>/application/controllers/Customer.php
<?php
class Customer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
$this->load->model('customer_model');
$this->load->model('old_customer_model');
$this->load->library('customer_lib');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/customer/overview'));
}
public function overview()
{
if ($this->input->post()) {
$this->form_validation->set_rules('name', '姓名', 'max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'is_natural|max_length[20]');
if ($this->form_validation->run() !== FALSE && (!empty($this->input->post('name')) || !empty($this->input->post('phone')))) {
$customers = $this->customer_model
->with_level()
->group_start()
->where('name', $this->input->post('name'), null, true)
->where('phone', $this->input->post('phone'), null, true)
->group_end()
->get();
if ($customers) {
redirect(base_url('/customer/consumer/' . $customers['id']));
}
}
}
$data = [
'title' => '消費者搜尋',
'view' => 'customer/overview',
];
$this->_preload($data);
}
public function old()
{
$total_customers_count = $this->old_customer_model
->where('isActive', 0)
->count_rows();
$customers = $this->old_customer_model
->where('isActive', 0)
->order_by('id', 'desc')
->paginate(20, $total_customers_count);
//權限設定
$authority = array();
if ($this->authentic->authority('customer', 'import')){
$authority['import'] = true;
}
if ($this->authentic->authority('customer', 'old_detail')){
$authority['old'] = true;
}
$data = [
'customers' => $customers,
'pagination' => $this->old_customer_model->all_pages,
'authority' => $authority,
'title' => '未轉換舊有會員資訊',
'view' => 'customer/old',
];
$this->_preload($data);
}
public function active_old()
{
$total_customers_count = $this->customer_model
->count_rows();
$customers = $this->customer_model
->with_level()
->order_by('id', 'desc')
->paginate(20, $total_customers_count);
$levels = $this->customer_level_model
->with_type()
->get_all();
//權限設定
$authority = array();
if ($this->authentic->authority('customer', 'consumer')){
$authority['consumer'] = true;
}
if ($this->authentic->authority('customer', 'old_detail')){
$authority['old'] = true;
}
if ($this->authentic->authority('customer', 'export')){
$authority['export'] = true;
}
$data = [
'levels' => $levels,
'customers' => $customers,
'pagination' => $this->customer_model->all_pages,
'authority' => $authority,
'title' => '會員資料區',
'view' => 'customer/active_old',
];
$this->_preload($data);
}
public function old_detail($old_customer_id)
{
$customer = $this->old_customer_model
->get($old_customer_id);
if (!$old_customer_id || !$customer) {
show_error('查無舊有會員資料');
}
$data = [
'customer' => $customer,
'title' => '舊有會員全部匯入資訊',
'view' => 'customer/old_detail',
];
$this->_preload($data);
}
public function consumer($customer_id)
{
if (!$customer_id) {
show_error('查無消費者資料');
}
$this->customer_lib->setCustomerID($customer_id);
$this->customer_lib->downgradeCheckCustomerLevel();
$customer = $this->customer_lib->getCustomer();
if (!$customer) {
show_error('查無消費者資料');
}
$this->load->model('order_model');
if ($this->dealer['retailer_id'] != 2){
$this->order_model->where('shipout_retailer_id', $this->dealer['retailer_id']);
}
$total_orders_count = $this->order_model
->where('buyer_type', 'customer')
->where('buyer_id', $customer_id)
->count_rows();
$sortby = (int)$this->input->get('sortby');
switch ($sortby){
case 2: //升序
$this->order_model->order_by($this->order_model->get_table_name().'.id', 'asc');
break;
case 3: //降序
$this->order_model->order_by($this->order_model->get_table_name().'.created_at', 'desc');
break;
case 4: //升序
$this->order_model->order_by($this->order_model->get_table_name().'.created_at', 'asc');
break;
case 5: //降序
$this->order_model->order_by($this->order_model->get_table_name().'.total', 'desc');
break;
case 6: //升序
$this->order_model->order_by($this->order_model->get_table_name().'.total', 'asc');
break;
case 7: //降序
$this->order_model->order_by($this->order_model->get_table_name().'.shipout_retailer_id', 'desc');
break;
case 8: //升序
$this->order_model->order_by($this->order_model->get_table_name().'.shipout_retailer_id', 'asc');
break;
default:
$this->order_model->order_by($this->order_model->get_table_name().'.id', 'desc');
break;
}
if ($this->dealer['retailer_id'] != 2){
$this->order_model->where('shipout_retailer_id', $this->dealer['retailer_id']);
}
$orders = $this->order_model
->with_retailer(['fields' => 'company'])
->where('buyer_type', 'customer')
->where('buyer_id', $customer_id)
->paginate(20, $total_orders_count);
//權限設定
$authority = array();
if ($this->authentic->authority('customer', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('consumer', 'add')){
$authority['consumer_add'] = true;
}
if ($this->authentic->authority('consumer', 'detail')){
$authority['consumer_detail'] = true;
}
$data = [
'customer' => $customer,
'orders' => $orders,
'pagination' => $this->customer_model->all_pages,
'authority' => $authority,
'title' => '該消費者歷史消費記錄',
'view' => 'customer/consumer',
];
$this->_preload($data);
}
public function upgrade($customer_id)
{
$this->customer_lib->setCustomerID($customer_id);
$customer = $this->customer_lib->getCustomer();
$customer_level_id = $this->customer_lib->upgradeLevel();
if (!$customer_level_id || $customer_level_id != 1) {
redirect(base_url('/customer/consumer/' . $customer_id));
}
if ($this->input->post()) {
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
$this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
$this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
$this->form_validation->set_rules('address', '地址', 'required|max_length[100]');
if ($this->form_validation->run() !== FALSE) {
$this->customer_model->update([
'customer_level_id' => 1,
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
'birthday' => $this->input->post('birthday'),
'email' => $this->input->post('email'),
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address'),
], ['id' => $customer_id]);
$this->customer_lib->saveLevelChangeHistory(1, 1);
redirect(base_url('/customer/consumer/' . $customer_id));
}
}
$levels = $this->customer_level_model
->with_type()
->get_all();
$data = [
'levels' => $levels,
'customer' => $customer,
'title' => '符合飄雪白卡資格',
'view' => 'customer/upgrade',
];
$this->_preload($data);
}
public function edit($customer_id)
{
$customer = $this->customer_model
->with_level()
->get($customer_id);
if (!$customer_id || !$customer) {
show_error('查無消費者資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
$this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
$this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
$this->form_validation->set_rules('address', '地址', 'required|max_length[100]');
if ($this->form_validation->run() !== FALSE) {
$this->customer_model->update([
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender') ? $this->input->post('gender') : null,
'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
'email' => $this->input->post('email') ? $this->input->post('email') : null,
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address') ? $this->input->post('address') : null,
], ['id' => $customer_id]);
redirect(base_url('/customer/consumer/' . $customer_id));
}
}
$data = [
'customer' => $customer,
'title' => '編輯消費者',
'view' => 'customer/edit',
];
$this->_preload($data);
}
public function conv_old($old_customer_id)
{
$customer = $this->old_customer_model
->with_customer()
->where('isActive', 0)
->get($old_customer_id);
if (!$old_customer_id || !$customer){
show_error('查無舊有會員資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('name', '姓名', 'required|max_length[20]');
$this->form_validation->set_rules('phone', '電話', 'required|is_natural|max_length[20]|valid_custom_phone[' . $customer_id . ']');
$this->form_validation->set_rules('gender', '性別', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('birthday_year', '生日年', 'integer|max_length[4]|min_length[4]');
$this->form_validation->set_rules('birthday', '生日', 'required|valid_date');
$this->form_validation->set_rules('email', 'Email', 'max_length[100]|valid_email');
$this->form_validation->set_rules('address', '地址', 'required|max_length[100]');
if ($this->form_validation->run() !== FALSE) {
$customer_id = $this->customer_model->insert([
'old_customer_id' => $old_customer_id,
'customer_level_id' => 2,
'name' => $this->input->post('name'),
'gender' => $this->input->post('gender') ? $this->input->post('gender') : null,
'birthday_year' => $this->input->post('birthday_year') ? $this->input->post('birthday_year') : null,
'birthday' => $this->input->post('birthday') ? date('Y') . '-' . $this->input->post('birthday') : null,
'email' => $this->input->post('email') ? $this->input->post('email') : null,
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address') ? $this->input->post('address') : null,
]);
$this->old_customer_model->update([
'isActive' => 1
], ['id' => $old_customer_id]);
redirect(base_url('/customer/consumer/' . $customer_id));
}
}
$data = [
'customer' => $customer,
'title' => '舊有會員轉換',
'view' => 'customer/conv_old',
];
$this->_preload($data);
}
public function import()
{
ini_set("memory_limit","2048M");
set_time_limit(0);
$error = '';
if (!empty($_FILES)) {
$config = [
'upload_path' => FCPATH . 'uploads/',
'allowed_types' => 'xls',
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('oldfile')) {
$error = $this->upload->display_errors();
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->library('excel');
$obj = PHPExcel_IOFactory::load($data['upload_data']['full_path']);
$cell = $obj->getActiveSheet()->getCellCollection();
$arr_data = [];
foreach ($cell as $cl){
$row = $obj->getActiveSheet()->getCell($cl)->getRow();
$data_value = $obj->getActiveSheet()->getCell($cl)->getValue();
if ($row != 1){
if (!isset($arr_data[$row])){
$arr_data[$row] = [];
}
$arr_data[$row][] = $data_value;
}
}
foreach ($arr_data as $r){
$customerNum = @$r[1];
$customerNum = trim($customerNum);
$name = @$r[2];
$name = trim($name);
$valid_at = @$r[3];
if (strtotime($valid_at) > 0){
$valid_at = date('Y-m-d', strtotime($valid_at));
} else {
$valid_at = null;
}
$expired_at = @$r[4];
if (strtotime($expired_at) > 0){
$expired_at = date('Y-m-d', strtotime($expired_at));
} else {
$expired_at = null;
}
$gender = @$r[5];
$gender = trim($gender);
if ($gender == '男性'){
$gender = 1;
} elseif ($gender == '女性'){
$gender = 0;
} else {
$gender = null;
}
$phone = @$r[6];
$phone = trim($phone);
$address = @$r[7];
$address = trim($address);
$email = @$r[8];
$email = trim($email);
$isVIP = @$r[13];
$isVIP = trim($isVIP);
if ($isVIP == 'VIP'){
$isVIP = 1;
} else {
$isVIP = 0;
}
$first_amount = @$r[15];
$first_amount = (int)$first_amount;
$accumulate_amount = @$r[17];
$accumulate_amount = (int)$accumulate_amount;
$total_amount = @$r[19];
$total_amount = (int)$total_amount;
$amount = 0;
if (!$total_amount){
$amount = $total_amount;
} elseif (!$accumulate_amount){
$amount = $accumulate_amount;
} elseif (!$first_amount){
$amount = $first_amount;
}
$buytimes = @$r[20];
$buytimes = (int)$buytimes;
if ($customerNum){
$total_customers_count = $this->old_customer_model
->where('customerNum', $customerNum)
->count_rows();
if (!$total_customers_count){
$this->old_customer_model->insert([
'customerNum' => $customerNum,
'name' => $name,
'valid_at' => $valid_at,
'expired_at' => $expired_at,
'gender' => $gender,
'phone' => $phone,
'address' => $address,
'email' => $email,
'isVIP' => $isVIP,
'amount' => $amount,
'buytimes' => $buytimes,
'isActive' => 0,
]);
}
}
}
@unlink($data['upload_data']['full_path']);
$this->session->set_userdata(array('msg' => '匯入成功'));
redirect(base_url('/customer/old/'));
}
}
$data = [
'error' => $error,
'title' => '匯入舊有會員資訊',
'view' => 'customer/import',
];
$this->_preload($data);
}
public function export($old = 0)
{
if ($old){
$this->customer_model->where('old_customer_id IS NOT NULL', null, null, false, false, true);
} else {
$this->customer_model->where('old_customer_id IS NULL', null, null, false, false, true);
}
$customers = $this->customer_model
->with_level()
->order_by('id', 'desc')
->get_all();
$data = array();
$data[] = array(
'會員等級',
'姓名',
'性別',
'生日',
'聯絡電話',
'Email',
'地址',
);
if ($customers) {
foreach ($customers as $customer) {
$data[] = array(
empty($customer['level']) ? '' : $customer['level']['title'],
$customer['name'],
is_null($customer['gender']) ? '' : gender($customer['gender']),
($customer['birthday_year'] ? $customer['birthday_year'] .'/' : '') . ($customer['birthday'] ? date('m/d', strtotime($customer['birthday'])) : ''),
$customer['phone'],
$customer['email'],
$customer['address'],
);
}
}
$this->load->helper('export_csv');
array_to_csv($data, "customer_".time());
exit;
}
}
?><file_sep>/application/migrations/005_add_order.php
<?php
//經銷商訂貨單
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_order extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'buyer_type' => [
'type' => 'VARCHAR',
'constraint' => 10,
'null' => TRUE,
],
'buyer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'shipout_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'serialNum' => [
'type' => 'VARCHAR',
'constraint' => 5,
],
'orderNum' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'totalQty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'subtotal' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'total' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'isConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'isPaid' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'isShipped' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
],
'dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_orders');
}
public function down()
{
$this->dbforge->drop_table('olive_orders');
}
}<file_sep>/application/views/stock_counting/overview.php
<div class="container">
<h1 class="mb-4"><?= $dealer['company'] ?>歷史盤點紀錄</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">盤點編號</th>
<th class="text-center">盤點事由</th>
<th class="text-center">承辦人</th>
<th></th>
</tr>
<?php
if ($stock_countings) {
foreach ($stock_countings as $stock_counting) {
?>
<tr>
<td class="text-center"><?= $stock_counting['countingNum'] ?></td>
<td class="text-center"><?= $counting_reason[$stock_counting['counting_reason']] ?></td>
<td class="text-center"><?= $stock_counting['dealer']['name'] ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['detail'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/stock_counting/detail/' . $stock_counting['id']) ?>">明細</a>
<?php if (!empty($stock_counting['description_file'])){ ?>
<button type="button" class="btn btn-info btn-sm dropdown-toggle dropdown-toggle-split"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="sr-only">Toggle Dropdown</span>
</button>
<div class="dropdown-menu">
<a class="dropdown-item" target="_blank" href="<?= base_url($stock_counting['description_file']) ?>">已簽名之盤點表</a>
</div>
<?php } ?>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="4" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/views/capital/promote/edit.php
<div class="container">
<h1 class="mb-4">編輯優惠活動</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">活動名稱</label>
<input name="title" class="form-control" value="<?= set_value('title', $promote['title']) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">開始</label>
<input type="date" name="start_at" class="form-control" value="<?= set_value('start_at', $promote['start_at']) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">結束</label>
<input type="date" name="end_at" class="form-control" value="<?= set_value('end_at', $promote['end_at']) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">可享用之優惠次數</label>
<input type="number" name="customer_limit" class="form-control text-right" value="<?= set_value('customer_limit', $promote['customer_limit']) ?>" min="1" />
</div>
<div class="form-group">
<label class="font-weight-bold">適用對象</label>
<select name="customer_type" class="form-control">
<?php foreach ($customer_type as $customer_type_id => $customer_type_title) { ?>
<option value="<?= $customer_type_id ?>"<?php if (set_value('customer_type', $promote['customer_type']) == $customer_type_id) echo 'selected';?>><?= $customer_type_title ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<label class="font-weight-bold">適用對象加入開始時間</label>
<input type="date" name="customer_start_at" class="form-control" value="<?= set_value('customer_start_at', $promote['customer_start_at']) ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">適用對象加入結束時間</label>
<input type="date" name="customer_end_at" class="form-control" value="<?= set_value('customer_end_at', $promote['customer_end_at']) ?>"/>
</div>
<div class="form-group">
<label class="font-weight-bold">不適用之營業單位</label>
<select id="exclude_retailers" name="exclude_retailers[]" class="form-control" multiple>
<?php foreach ($retailers as $retailer) { ?>
<option value="<?= $retailer['id'] ?>" <?php if (set_value('exclude_retailers', $promote['exclude_retailers']) && in_array($retailer['id'], set_value('exclude_retailers', $promote['exclude_retailers']))){ echo 'selected';} ?>><?= $retailer['company'] ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="checkbox" id="go_with_member" value="1" name="go_with_member"<?php if (set_value('go_with_member', $promote['go_with_member'])){ echo ' checked';} ?>>
<label class="form-check-label" for="go_with_member">該優惠活動可與會員優惠同時使用</label>
</div>
<div class="form-group">
<input type="checkbox" id="go_with_coupon" value="1" name="go_with_coupon"<?php if (set_value('go_with_coupon', $promote['go_with_coupon'])){ echo ' checked';} ?>>
<label class="form-check-label" for="go_with_coupon">該優惠活動可與貴賓優惠券同時使用</label>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/capital_promote/overview/') ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css"
integrity="<KEY> crossorigin="anonymous"/>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css"
integrity="<KEY> crossorigin="anonymous"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"
integrity="<KEY> crossorigin="anonymous"></script>
<script>
$().ready(function () {
$('#exclude_retailers').select2({
theme: "bootstrap",
multiple: true,
placeholder: '選擇不適用之營業單位'
});
});
</script><file_sep>/application/migrations/049_add_promote_v2.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_promote_v2 extends CI_Migration {
public function up()
{
$this->dbforge->drop_table('olive_promotes');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'start_at' => [
'type' => 'date',
'null' => TRUE,
],
'end_at' => [
'type' => 'date',
'null' => TRUE,
],
'exclude_retailers' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => TRUE,
],
'customer_type' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'null' => TRUE,
],
'customer_limit' => [
'type' => 'smallint',
'unsigned' => TRUE,
'null' => TRUE,
],
'customer_start_at' => [
'type' => 'date',
'null' => TRUE,
],
'customer_end_at' => [
'type' => 'date',
'null' => TRUE,
],
'go_with_member' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'default' => 0,
],
'go_with_coupon' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promotes');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'promote_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'promote_type_id' => [
'type' => 'tinyint',
'constraint' => 2,
'unsigned' => TRUE,
],
'discount_type' => [
'type' => 'CHAR',
'constraint' => 1,
'default' => 'P',
],
'discount' => [
'type' => 'int',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'limit' => [
'type' => 'int',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'sort' => [
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promote_methods');
$this->dbforge->drop_table('olive_promote_items');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'promote_method_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_type' => [
'type' => 'VARCHAR',
'constraint' => 10,
'default' => 'product',
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promote_items');
$this->dbforge->drop_table('olive_promote_item_relatives');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'promote_method_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_type' => [
'type' => 'VARCHAR',
'constraint' => 10,
'default' => 'product',
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promote_item_relatives');
}
public function down()
{
$this->dbforge->drop_table('olive_promotes');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'promote_type_id' => [
'type' => 'tinyint',
'constraint' => 2,
'unsigned' => TRUE,
],
'title' => [
'type' => 'VARCHAR',
'constraint' => 100,
],
'start_at' => [
'type' => 'date',
'null' => TRUE,
],
'end_at' => [
'type' => 'date',
'null' => TRUE,
],
'exclude_retailers' => [
'type' => 'VARCHAR',
'constraint' => 255,
'null' => TRUE,
],
'discount_type' => [
'type' => 'CHAR',
'constraint' => 1,
'default' => 'P',
],
'discount' => [
'type' => 'int',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'limit' => [
'type' => 'int',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'customer_type' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'null' => TRUE,
],
'customer_limit' => [
'type' => 'smallint',
'unsigned' => TRUE,
'null' => TRUE,
],
'customer_start_at' => [
'type' => 'date',
'null' => TRUE,
],
'customer_end_at' => [
'type' => 'date',
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promotes');
$this->dbforge->drop_table('olive_promote_methods');
$this->dbforge->drop_table('olive_promote_items');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'promote_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_type' => [
'type' => 'VARCHAR',
'constraint' => 10,
'default' => 'product',
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promote_items');
$this->dbforge->drop_table('olive_promote_item_relatives');
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'promote_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_type' => [
'type' => 'VARCHAR',
'constraint' => 10,
'default' => 'product',
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_promote_item_relatives');
}
}<file_sep>/application/migrations/010_add_shipment_item.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_shipment_item extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'shipment_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'price' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'subtotal' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'discount' => [
'type' => 'INT',
'constraint' => 3,
'unsigned' => TRUE,
'default' => 100,
],
'total' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_shipment_items');
}
public function down()
{
$this->dbforge->drop_table('olive_shipment_items');
}
}<file_sep>/application/views/guest/level.php
<div class="container">
<div class="row">
<div class="col-md-12">
<h1 class="mb-4">點選經銷商類別</h1>
<form id="register_form" method="post">
<div class="form-group">
<p>經銷商資格限定:</p>
<p>所有營業單位以及任何營業單位的所屬人員(員工、股東)都不能成為經銷商</p>
<p>※營業單位:包含總代理、總經銷、總代理百貨櫃位、總代理門市、皮瑪斯門市、個人經銷商、店面經銷商、櫃位經銷商</p>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck" required>
<label class="form-check-label" for="gridCheck">
已詳閱經銷商資格限定中之內容
</label>
</div>
</div>
<?php
if ($retailer_level_types) {
foreach ($retailer_level_types as $type => $retailer_level_type) {
?>
<div class="form-group text-center">
<?php if (empty($retailer_level_type['levels'])){ ?>
<button name="type" class="btn-type btn btn-success" value="<?=$type?>" disabled><?=$retailer_level_type['title']?>(規劃中,敬請期待)</button>
<?php } else { ?>
<button name="type" class="btn-type btn btn-success" value="<?=$type?>"><?=$retailer_level_type['title']?></button>
<?php } ?>
</div>
<?php
}
}
?>
</form>
</div>
</div>
</div><file_sep>/application/views/shipment/confirm.php
<div class="container">
<h1 class="mb-4">確認進貨單 <?= $purchase['purchaseNum'] ?> 收貨</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>進貨單編號</th>
<td><?= $purchase['purchaseNum'] ?></td>
<th>訂貨日期</th>
<td><?= $purchase['created_at'] ?></td>
</tr>
<tr>
<th>出貨單位</th>
<td><?= $purchase['shipout_retailer']['company'] ?></td>
<th>出貨單位回覆</th>
<td><?=$purchase['confirm_label']?></td>
</tr>
<tr>
<th>出貨決定</th>
<td><?=$purchase['shipped_label']?></td>
<th>進貨日期</th>
<td><?=$purchase['shipped_at']?></td>
</tr>
<tr>
<th>進貨單位付款</th>
<td><?=$purchase['paid_label']?></td>
<th>進貨付款日期</th>
<td><?=$purchase['paid_at']?></td>
</tr>
<tr>
<th>進貨單位</th>
<td><?= $purchase['retailer']['invoice_title'] ?></td>
<th>進貨單位地址</th>
<td><?= $purchase['retailer_address'] ?></td>
</tr>
<tr>
<th>收貨對象</th>
<td><?= $purchase['shipin_retailer']['invoice_title'] ?></td>
<th>收貨地址</th>
<td>
<?php
echo $purchase['shipin_address'];
if (!$purchase['isMatchBox']){
echo '<div class="text-danger">取貨方式限定親自至輔銷單位取貨</div>';
}
?>
</td>
</tr>
<?php if ($purchase['isInvoice']){ ?>
<tr>
<th>發票對象</th>
<td colspan="3"><?= $purchase['invoice_retailer'] ?></td>
</tr>
<tr>
<th>發票寄送對象</th>
<td><?= $purchase['invoice_send_retailer'] ?></td>
<th>發票寄送地址</th>
<td><?= $purchase['invoice_send_address'] ?></td>
</tr>
<?php } ?>
<tr>
<th>進貨方之備註</th>
<td><?= nl2br($purchase['memo']) ?></td>
<th>出貨方之備註</th>
<td><?= nl2br($shipment['memo']) ?></td>
</tr>
</table>
<form method="post" id="shipmentForm" enctype="multipart/form-data">
<h4 class="my-4 text-center">進貨明細</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th>項次</th>
<th>貨品編號 / 貨品名稱</th>
<th>訂購數量</th>
<th>到期日</th>
<th>出貨數量</th>
<th>收貨數量</th>
<th>備註</th>
<th>照片</th>
</tr>
<?php
if ($shipment['items']) {
$i = 1;
foreach ($shipment['items'] as $item) {
if (empty($products[$item['product_id']])){
continue;
}
$stock_row = count($products[$item['product_id']]);
?>
<tr>
<td class="text-center" rowspan="<?=$stock_row?>"><?= $i ?></td>
<td rowspan="<?=$stock_row?>"><?= $item['product']['p_num'] ?> <br /><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td class="text-right" rowspan="<?=$stock_row?>"><?= number_format($item['qty']) ?></td>
<?php
foreach ($products[$item['product_id']] as $key => $stock){
if ($key > 0){
echo '</tr><tr>';
}
?>
<td><?=$stock['expired_at'] ? $stock['expired_at'] : '未標示'?></td>
<td class="text-right"><?= $stock['qty'] ?></td>
<td class="text-center">
<input type="number" min="0" data-stock="<?=$stock['qty']?>" class="input_qty form-control text-right" name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][qty]" value="<?= $stock['qty'] ?>" style="width: 120px;" />
</td>
<td class="text-center">
<textarea disabled name="items[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>][memo]" class="text_qty_memo form-control" style="min-width: 120px;"></textarea>
</td>
<td>
<input disabled type="file" class="input_qty_file form-control-file" name="memo_pictures[<?= $item['product_id'] ?>][<?=$stock['expired_at']?>]" style="min-width: 120px;" />
</td>
<?php } ?>
</tr>
<?php
$i++;
}
}
?>
</table>
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group text-center">
<a href="<?=base_url('/purchase/overview/')?>" class="btn btn-secondary">取消</a>
<input type="submit" name="confirmed" class="btn btn-success" value="送出收貨狀態"/>
</div>
</form>
</div>
<script>
$().ready(function () {
$('.input_qty').change(function(){
var shipin_qty = parseInt($(this).val()) || 0;
var stock_qty = parseInt($(this).data('stock')) || 0;
if (shipin_qty != stock_qty){
$(this).parents('tr').find('.text_qty_memo').prop('disabled', false);
$(this).parents('tr').find('.input_qty_file').prop('disabled', false);
} else {
$(this).parents('tr').find('.text_qty_memo').prop('disabled', true);
$(this).parents('tr').find('.input_qty_file').prop('disabled', true);
}
});
$("#shipmentForm").submit(function (e) {
$.each($('input.input_qty'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('textarea.text_qty_memo'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
$.each($('input.input_qty_file'), function () {
if ($(this).val() == '') {
$(this).prop('disabled', true);
}
});
});
});
</script><file_sep>/application/views/capital/privilege/authority.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">
<?= $class_list[$classname]['alias'] . ' (' . $class_list[$classname]['method'][$methodname] ?>) 權限
</h1>
<form method="post">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th class="text-left">群組名稱</th>
<th class="text-center">權限設定</th>
</tr>
</thead>
<tbody>
<?php
if ($groups) {
foreach ($groups as $group_id => $group) {
?>
<tr>
<td><?= (empty($group['level_type']) ? $group['role']['title'] : $group['level_type']['title']) . ' - ' . $group['title'] ?></td>
<td class="text-center">
<select name="rules[<?=$group_id?>]" class="form-control">
<?php foreach ($permission as $k => $v) { ?>
<option value="<?= $k ?>"<?php if ($k == $group['permission']) {
echo 'selected';
} ?>><?= $v ?></option>
<?php } ?>
</select>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/capital_privilege/apps/' . $classname) ?>" class="btn btn-light">取消</a>
<input type="submit" value="更新" class="btn btn-primary"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/core/MY_Controller.php
<?php
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function _preload($data = [], $layout = 'default')
{
//權限
if (!in_array($this->router->fetch_class(), ['auth', 'db', 'index'])) {
if (!$this->authentic->authority($this->router->fetch_class(), $this->router->fetch_method())){
show_error('您沒有瀏覽此頁面的權限');
}
}
$message = $this->session->userdata('msg');
if (!empty($message)) {
$data['msg'] = $message;
$this->session->unset_userdata('msg');
}
$data['dealer'] = $this->authentic->isLogged();
$data['title'] = (!empty($data['title']) ? $data['title'] . '-' : '') . $this->config->item('app_title');
if ($layout == 'default'){
$menu = [];
if ($this->authentic->authority('purchase', 'overview')) {
$menu[] = [
'title' => '進貨單',
'url' => base_url('/purchase/overview'),
];
}
if ($this->authentic->authority('transfer', 'overview')) {
$menu[] = [
'title' => '出貨單',
'url' => base_url('/transfer/overview'),
];
}
$submenu = [];
if ($this->authentic->authority('payment', 'overview')) {
$submenu[] = [
'url' => base_url('/payment/overview'),
'title' => '付款紀錄列表',
];
}
if ($this->authentic->authority('payment', 'confirms')) {
$submenu[] = [
'url' => base_url('/payment/confirms'),
'title' => '待確認收款',
];
}
if ($submenu) {
$menu[] = [
'title' => '付款',
'submenu' => $submenu,
];
}
$submenu = [];
if ($this->authentic->authority('stock', 'overview')) {
$submenu[] = [
'url' => base_url('/stock/overview'),
'title' => '即時庫存',
];
}
if ($this->authentic->authority('stock_counting', 'index')) {
$submenu[] = [
'url' => base_url('/stock_counting/index'),
'title' => '盤點作業',
];
}
if ($submenu) {
$menu[] = [
'title' => '庫存',
'submenu' => $submenu,
];
}
if ($this->authentic->authority('supervisor', 'overview')) {
$menu[] = [
'title' => '經銷商列表',
'url' => base_url('/supervisor/overview'),
];
}
if (!empty($data['dealer']['retailers'])) {
$submenu = [];
if ($this->authentic->authority('commission', 'dealers')) {
$submenu[] = [
'url' => base_url('/commission/dealers'),
'title' => '輔銷人',
];
}
if ($submenu) {
$menu[] = [
'title' => '輔銷獎金',
'submenu' => $submenu,
];
}
}
if ($this->authentic->authority('customer', 'overview')) {
$submenu = [];
if ($this->authentic->authority('consumer', 'add')) {
$submenu[] = [
'url' => base_url('/consumer/add'),
'title' => '消費者訂購',
];
}
if ($this->authentic->authority('consumer')) {
$submenu[] = [
'url' => base_url('/consumer'),
'title' => '消費紀錄',
];
}
if ($this->authentic->authority('consumer', 'old')) {
$submenu[] = [
'url' => base_url('/consumer/old'),
'title' => '舊有會員轉換',
];
}
if ($this->authentic->authority('customer', 'old')) {
$submenu[] = [
'url' => base_url('/customer/old'),
'title' => '未轉換舊有會員',
];
}
if ($this->authentic->authority('customer', 'active_old')) {
$submenu[] = [
'url' => base_url('/customer/active_old'),
'title' => '會員資料區',
];
}
if ($this->authentic->authority('consumer', 'payAtShipped')) {
$submenu[] = [
'url' => base_url('/consumer/payAtShipped'),
'title' => '貨到付款管理',
];
}
if ($this->authentic->authority('consumer', 'transfer')) {
$submenu[] = [
'url' => base_url('/consumer/transfer'),
'title' => 'A店買B店取貨',
];
}
if ($submenu) {
$menu[] = [
'title' => '消費者',
'submenu' => $submenu,
];
}
}
if ($this->authentic->authority('recommend', 'overview')) {
$submenu = [];
if ($this->authentic->authority('recommend', 'add')) {
$submenu[] = [
'url' => base_url('/recommend/add'),
'title' => '來賓推薦作業',
];
}
if ($this->authentic->authority('recommend_template')) {
$submenu[] = [
'url' => base_url('/recommend_template'),
'title' => '推薦函之增修',
];
}
if ($this->authentic->authority('recommend', 'overview')) {
$submenu[] = [
'url' => base_url('/recommend/overview'),
'title' => '行銷作業區',
];
}
if ($this->authentic->authority('recommend', 'temp')) {
$submenu[] = [
'url' => base_url('/recommend/temp'),
'title' => '暫存作業區',
];
}
if ($submenu) {
$menu[] = [
'title' => '行銷管理',
'submenu' => $submenu,
];
}
}
$submenu = [];
if ($this->authentic->authority('income', 'overview')) {
$submenu[] = [
'url' => base_url('/income/overview/'),
'title' => '營業資訊',
];
}
if ($this->authentic->authority('income', 'product')) {
$submenu[] = [
'url' => base_url('/income/product/'),
'title' => '產品業績',
];
}
if ($submenu) {
$menu[] = [
'title' => '財務管理',
'submenu' => $submenu,
];
}
$submenu = [];
if ($this->authentic->authority('retailer', 'overview')) {
$submenu[] = [
'url' => base_url('/retailer/overview'),
'title' => '人事管理',
];
}
if ($this->authentic->authority('capital_stock', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_stock/overview'),
'title' => '單位庫存',
];
}
if ($this->authentic->authority('capital_product', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_product/overview'),
'title' => '商品管理',
];
}
if ($this->authentic->authority('capital_combo', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_combo/overview'),
'title' => '商品組合管理',
];
}
if ($this->authentic->authority('capital_free_package', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_free_package/overview'),
'title' => '免費包裝管理',
];
}
if ($this->authentic->authority('capital_promote', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_promote/overview'),
'title' => '優惠活動管理',
];
}
// if ($this->authentic->authority('coupon', 'confirm')) {
// $submenu[] = [
// 'url' => base_url('/coupon/confirm'),
// 'title' => '折價券審核',
// ];
// }
if ($this->authentic->authority('capital_retailer', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_retailer/overview'),
'title' => '單位管理',
];
}
if ($this->authentic->authority('capital_retailer_role', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_retailer_role/overview'),
'title' => '單位群組管理',
];
}
if ($this->authentic->authority('capital_privilege', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_privilege/overview'),
'title' => '權限管理',
];
}
if ($this->authentic->authority('capital_level', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_level/overview'),
'title' => '經銷規則管理',
];
}
if ($this->authentic->authority('capital_level_type', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_level_type/overview'),
'title' => '經銷類別管理',
];
}
if ($this->authentic->authority('capital_customer_level', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_customer_level/overview'),
'title' => '會員資格管理',
];
}
if ($this->authentic->authority('capital_pao', 'overview')) {
$submenu[] = [
'url' => base_url('/capital_pao/overview'),
'title' => '商品期限參數',
];
}
if ($this->authentic->authority('capital_option', 'customer')) {
$submenu[] = [
'url' => base_url('/capital_option/customer'),
'title' => '消費者參數',
];
}
if ($submenu) {
$menu[] = [
'title' => '設定',
'submenu' => $submenu,
];
}
$data['menu'] = $menu;
$right_menu = [];
$submenu = [];
if ($this->authentic->authority('dealer', 'edit')) {
$submenu[] = [
'url' => base_url('/dealer/edit'),
'title' => '單位資料修改',
];
}
if ($this->authentic->authority('dealer', 'profile')) {
$submenu[] = [
'url' => base_url('/dealer/profile'),
'title' => '個人資料修改',
];
}
if ($this->authentic->authority('dealer', 'password')) {
$submenu[] = [
'url' => base_url('/dealer/password'),
'title' => '密碼修改',
];
}
if ($submenu) {
$right_menu[] = [
'title' => '<i class="fas fa-user-circle"></i>',
'submenu' => $submenu,
];
}
$right_menu[] = [
'title' => '登出',
'url' => base_url('/auth/logout'),
];
$data['right_menu'] = $right_menu;
}
$this->load->view('layout/' . $layout, $data);
}
}
<file_sep>/application/models/Retailer_level_model.php
<?php
class Retailer_level_model extends MY_Model
{
public $table = 'olive_retailer_levels';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['retailers'] = array('Retailer_model', 'retailer_level_id', 'id');
$this->has_one['type'] = array('foreign_model' => 'Retailer_level_type_model', 'foreign_table' => 'olive_retailer_level_types', 'foreign_key' => 'id', 'local_key' => 'retailer_level_type_id');
}
public function getLevelSelect()
{
$_levels = $this
->with_type()
->get_all();
$levels = [];
foreach ($_levels as $level){
$levels[$level['id']] = $level['type']['title'] . ' ' . $level['code'];
}
return $levels;
}
}
?>
<file_sep>/application/views/retailer/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增<?= $dealer['company'] ?>人員</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>群組</label>
<?php
echo form_dropdown('retailer_group_id', $groups, set_value('retailer_group_id'), 'class="form-control"');
?>
</div>
<div class="form-group">
<label>帳號</label>
<input name="account" class="form-control" minlength="3" maxlength="10" required value="<?= set_value('account') ?>" style="text-transform: lowercase;" />
</div>
<div class="form-group">
<label>姓名</label>
<input name="name" class="form-control" maxlength="20" required value="<?= set_value('name') ?>" />
</div>
<div class="form-group">
<label>性別</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_1"
value="1"<?= set_value('gender') == '1' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_1">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" id="gender_0"
value="0"<?= set_value('gender') === '0' ? ' checked' : '' ?>>
<label class="form-check-label" for="gender_0">女</label>
</div>
</div>
</div>
<div class="form-group">
<label>登入密碼</label>
<input type="<PASSWORD>" name="password" class="form-control" value="" required />
</div>
<div class="form-group">
<label>確認密碼</label>
<input type="password" name="password_confirm" class="form-control" value="" required />
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/retailer/overview')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/dealer/password.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">密碼修改</h1>
<form method="post">
<?php if (validation_errors()){ ?>
<div class="alert alert-danger">
<?=validation_errors()?>
</div>
<?php } ?>
<div class="form-group">
<label>舊密碼</label>
<input type="password" name="password_old" class="form-control" value="" />
</div>
<div class="form-group">
<label>登入密碼</label>
<input type="<PASSWORD>" name="password" class="form-control" value="" />
</div>
<div class="form-group">
<label>確認密碼</label>
<input type="<PASSWORD>" name="password_confirm" class="form-control" value="" />
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-success" value="更新"/>
</div>
</form>
</div>
</div>
</div>
<file_sep>/application/models/Commission_model.php
<?php
class Commission_model extends MY_Model
{
public $table = 'olive_commissions';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['retailers'] = array('Retailer_model', 'id', 'commission_id');
$this->has_many['dealers'] = array('Dealer_model', 'id', 'commission_id');
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
}
//計算進貨傭金
public function record($purchase_id)
{
$this->load->model('purchase_model');
$purchase = $this->purchase_model
->with_retailer(['with' => ['relation' => 'level']])
->get($purchase_id);
if ($purchase && $purchase['isShipConfirmed']){
//如果原本有計算傭金紀錄則刪除重算
$this->where('purchase_id', $purchase_id)->delete();
//計算獎金
$this->load->model('dealer_model');
$this->load->model('commission_model');
$allowance_payment_total = $this->purchase_model->sumPurchaseAllowance($purchase_id);
$total = $purchase['total'] - $allowance_payment_total;
//輔銷人
$sales_dealer_id = empty($purchase['retailer']['sales_dealer_id']) ? '' : $purchase['retailer']['sales_dealer_id'];
$sales_dealer = $this->dealer_model
->get($sales_dealer_id);
//輔銷人獎金
if ($sales_dealer && !empty($purchase['retailer']['level'])) {
$commission_rate = 0; //大於75%折扣不給獎金
if ($purchase['retailer']['level']['discount'] < 60) {
$commission_rate = 2;
} elseif ($purchase['retailer']['level']['discount'] < 75) {
$commission_rate = 3;
}
$commission = round($total * $commission_rate / 100);
if ($commission) {
$this->insert([
'commission_type' => 'dealer',
'commission_id' => $sales_dealer_id,
'purchase_id' => $purchase_id,
'total' => $commission,
]);
}
}
}
}
}
?>
<file_sep>/application/models/Combo_model.php
<?php
class Combo_model extends MY_Model
{
public $table = 'olive_combos';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['items'] = array('Combo_item_model', 'combo_id', 'id');
}
public function getAllCombos()
{
$_combos = $this
->get_all();
$combos = [];
if ($_combos) {
foreach ($_combos as $c) {
$c['qty'] = '';
$combos[$c['id']] = $c;
}
}
return $combos;
}
}
?>
<file_sep>/application/migrations/014_add_customer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_customer extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'old_customer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => true,
],
'customer_level_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => true,
],
'name' => [
'type' => 'VARCHAR',
'constraint' => 20,
],
'gender' => [
'type' => 'tinyint',
'unsigned' => TRUE,
'constraint' => 1,
'null' => true,
],
'birthday_year' => [
'type' => 'smallint',
'constraint' => 4,
'null' => true,
],
'birthday' => [
'type' => 'date',
'null' => true,
],
'email' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'phone' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => true,
],
'address' => [
'type' => 'VARCHAR',
'constraint' => 100,
'null' => true,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_customers');
}
public function down()
{
$this->dbforge->drop_table('olive_customers');
}
}<file_sep>/application/models/Dealer_history_model.php
<?php
class Dealer_history_model extends MY_Model
{
public $table = 'dealer_history';
public $primary_key = 'autoid';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->return_as = 'array';
}
}
?>
<file_sep>/application/models/Product_permission_model.php
<?php
class Product_permission_model extends MY_Model
{
public $table = 'olive_product_permissions';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
}
public function getPermissionProducts($retailer_id = '')
{
$this->load->model('product_model');
$products = $this->product_model->getProducts();
if ($products){
$_permissions = $this->get_all();
$permissions = [];
if ($_permissions){
foreach ($_permissions as $k => $p){
$retailers = is_null($p['include_retailers']) ? null : explode(',', $p['include_retailers']);
$p['retailers'] = $retailers;
$permissions[$p['product_id']] = $p;
}
}
foreach ($products as $product_id => $product){
if (isset($permissions[$product_id])) {
if ($permissions[$product_id]['retailers'] && (!$retailer_id || !in_array($retailer_id, $permissions[$product_id]['retailers']))) {
unset($products[$product_id]);
}
}
}
}
return $products;
}
}
?>
<file_sep>/application/views/supervisor/overview.php
<div class="container">
<h1 class="mb-4">經銷商列表</h1>
<p>起算日至結算日: <?=$search['year'].'/'.$search['month'].'/1~'.$search['month'].'/'.date("t", strtotime($search['year'].'/'.$search['month'].'/1'))?></p>
<?php if ($dealer['sales_retailer']){ ?>
<p>輔銷單位: <?= $dealer['sales_retailer']['company'] ?></p>
<?php } ?>
<form id="search_form">
<div class="card mb-4">
<div class="card-header">搜尋</div>
<div class="card-body">
<div class="form-row">
<div class="form-group col-md-3">
<label for="year">年度</label>
<input type="number" min="2018" max="<?=date('Y')?>" class="form-control text-right" name="year" value="<?=$search['year']?>" />
</div>
<div class="form-group col-md-3">
<label for="month">月份</label>
<input type="number" min="1" max="12" class="form-control text-right" name="month" value="<?=$search['month']?>" />
</div>
<div class="form-group col-md-3">
<label for="created_start">經銷商類別</label>
<?php
echo form_dropdown('retailer_level_id', ['' => ''] + $retailer_level_selects, $search['retailer_level_id'], 'class="form-control"');
?>
</div>
<div class="form-group col-md-3">
<label for="created_start">門檻</label>
<?php
echo form_dropdown('threshold_category', ['' => ''] + $threshold_categories, $search['threshold_category'], 'class="form-control"');
?>
</div>
<div class="form-group col-md-3">
<label class="font-weight-bold">經銷商是否失效</label>
<?php
echo form_dropdown('disabled', ['0' => '否', '1' => '是'], $search['disabled'], 'class="form-control"');
?>
</div>
<?php if ($sales_retailer_select){ ?>
<div class="form-group col-md-3">
<label for="sales_retailer_id">輔銷單位</label>
<?php
echo form_dropdown('sales_retailer_id', ['' => ''] + $sales_retailer_select, $search['sales_retailer_id'], 'class="form-control"');
?>
</div>
<?php } ?>
<?php if ($sales_dealer_select){ ?>
<div class="form-group col-md-3">
<label for="sales_dealer_id">輔銷人</label>
<?php
echo form_dropdown('sales_dealer_id', ['' => ''] + $sales_dealer_select, $search['sales_dealer_id'], 'class="form-control"');
?>
</div>
<?php } ?>
</div>
</div>
<div class="card-footer text-center">
<input type="submit" value="搜尋" class="btn btn-primary" />
<a href="<?=base_url('/supervisor/overview')?>" class="btn btn-light">重設</a>
</div>
</div>
</form>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th></th>
<th class="text-center">輔銷單位</th>
<th class="text-center">輔銷人</th>
<th class="text-center">經銷商名稱</th>
<th class="text-center">經銷商類別</th>
<th class="text-center">每月進貨門檻</th>
<th class="text-center">本月已進貨金額</th>
<th class="text-center">未達門檻之金額</th>
<th class="text-center">
超過門檻之金額 (<a href="#" data-toggle="modal" data-target="#thresholdModal">說明</a>)
</th>
<th></th>
</tr>
<?php
if ($retailers) {
foreach ($retailers as $retailer) {
?>
<tr>
<td class="text-center"><?php if ($retailer['first']){ echo '首次進貨'; } ?></td>
<td class="text-center"><?= empty($retailer['sales_retailer']) ? '' : $retailer['sales_retailer']['company'] ?></td>
<td class="text-center"><?= empty($retailer['sales_dealer']) ? '' : $retailer['sales_dealer']['name'] ?></td>
<td class="text-center">
<?php if (!empty($authority['info'])){ ?>
<a href="<?= base_url('/supervisor/info/' . $retailer['id']) ?>">
<?= $retailer['company'] ?>
</a>
<?php } else { ?>
<?= $retailer['company'] ?>
<?php } ?>
<?php if (!is_null($retailer['disabled_at'])){ ?>
<br /><span class="text-danger">失效月份<?= date('Y/m', strtotime($retailer['disabled_at'])) ?></span>
<?php } ?>
</td>
<td class="text-center"><?= $retailer['level_title'] ?></td>
<td class="text-center"><?= $retailer['threshold'] ?></td>
<td class="text-center">$<?= number_format($retailer['total']) ?></td>
<td class="text-center">$<?= number_format($retailer['under']) ?></td>
<td class="text-center">$<?= number_format($retailer['over']) ?></td>
<td class="text-center">
<div class="btn-group" role="group">
<?php if (!empty($authority['purchase'])){ ?>
<a class="btn btn-info btn-sm"
href="<?= base_url('/supervisor/purchase/' . $retailer['id'] . '/' . $search['year'] . '/' . $search['month']) ?>">
進貨明細
</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="10" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div>
<div class="modal fade" id="thresholdModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<p>超過「每月進貨門檻」之金額將計入下月「本月已進貨金額」中。</p>
</div>
</div>
</div>
</div><file_sep>/application/views/consumer/shipping.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">貨到付款確認寄出</h1>
<form method="post" enctype="multipart/form-data">
<?php if ($error) { ?>
<div class="alert alert-danger">
<?= implode('<br>', $error) ?>
</div>
<?php } ?>
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">收貨人</label>
<div><?=$order['recipient']['name']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">連絡電話</label>
<div><?=$order['recipient']['phone']?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">收貨地址</label>
<div><?=$order['recipient']['address']?></div>
</div>
<h4 class="my-4 text-center">貨品內容</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>貨品名稱</td>
<td>訂購數量</td>
<td>庫存到期日</td>
<td>庫存數量</td>
<td>出貨數量</td>
</tr>
<?php
if ($products) {
foreach ($products as $product_id => $product) {
$stock_row = count($product['stocks']);
?>
<tr>
<td rowspan="<?=$stock_row?>" class="align-middle"><?= $product['name'] ?></td>
<td rowspan="<?=$stock_row?>" class="align-middle text-right"><?= number_format($product['qty']) ?></td>
<?php if (empty($product['stocks'])){ ?>
<td class="align-middle"></td>
<td class="align-middle">無庫存</td>
<td class="align-middle"></td>
<?php
} else {
foreach ($product['stocks'] as $k => $stock) {
$qty = min($product['qty'], $product['stocks'][0]['stock']);
if ($k > 0) {
echo '</tr><tr>';
}
?>
<td class="align-middle"><?= $stock['expired_at'] ? $stock['expired_at'] : '未標示' ?></td>
<td class="align-middle text-right"><?= number_format($stock['stock']) ?></td>
<td class="align-middle">
<input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$stock['expired_at']?>]" max="<?=$product['qty']?>" min="0" value="<?=$qty?>" />
</td>
<?php
if ($product['qty'] == $qty) {
$product['qty'] = 0;
} else {
$product['qty'] -= $qty;
}
}
}
?>
</tr>
<?php
}
}
?>
</table>
<div class="form-group">
<label class="font-weight-bold">運費</label>
<input type="number" name="freight" class="form-control text-right"
value="<?= set_value('freight', 0) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">手續費</label>
<input type="number" name="fare" class="form-control text-right"
value="<?= set_value('fare', 0) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">寄出貨品之憑證</label>
<input type="file" class="form-control-file" name="product_verify" />
</div>
<div class="form-group">
<label class="font-weight-bold">運費及手續費憑證</label>
<input type="file" class="form-control-file" name="fare_verify" />
</div>
<div class="form-group">
<label class="font-weight-bold">出貨時之佐證</label>
<input type="file" class="form-control-file" name="shipment_verify" />
</div>
<div class="form-group">
<label class="font-weight-bold">備註</label>
<textarea rows="5" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="確認寄出"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/capital/pao/add.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">新增商品期限參數</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>有效期限</label>.
<div class="input-group">
<input type="number" name="expiration_month" class="form-control text-right" value="<?= set_value('expiration_month', 1) ?>" required min="1" />
<div class="input-group-append">
<span class="input-group-text">月</span>
</div>
</div>
</div>
<div class="form-group">
<label>PAO</label>
<div class="input-group">
<input type="number" name="pao_month" class="form-control text-right" value="<?= set_value('pao_month', 0) ?>" required min="0" />
<div class="input-group-append">
<span class="input-group-text">月</span>
</div>
</div>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/capital_pao/overview/')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="新增"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/capital/privilege/overview.php
<div class="container">
<h1 class="mb-4">權限總覽</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<thead>
<tr>
<th class="text-left">頁面名稱</th>
<th class="text-center"></th>
</tr>
</thead>
<tbody>
<?php
if ($class_list) {
foreach ($class_list as $classname => $item) {
?>
<tr>
<td class="text-left"><?= $item['alias'] ?></td>
<td class="text-center">
<div class="btn-group">
<?php if (!empty($authority['apps'])){ ?>
<a class="btn btn-info"
href="<?= base_url('/capital_privilege/apps/' . $classname) ?>">動作總覽</a>
<?php } ?>
</div>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="2" class="text-center">查無資料</td>
</tr>
<?php } ?>
</tbody>
</table>
</div><file_sep>/application/views/capital/stock/detail.php
<div class="container">
<h1 class="mb-4"><?= $retailer['company'] ?> 詳細 <?= $product['pdName'] ?> <?= $product['intro2'] ?> 庫存</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">正常品</th>
<th class="text-center">即期品</th>
<th class="text-center">過期品</th>
<th class="text-center">未標到期日</th>
</tr>
<tr>
<td class="p-0">
<table class="table table-hover table-bordered mb-0">
<tr>
<td>數量</td>
<td>到期日</td>
</tr>
<?php
if ($product['stock']['normal']['data']) {
foreach ($product['stock']['normal']['data'] as $s) {
?>
<tr>
<td class="text-right"><?=number_format($s['stock'])?></td>
<td><?=$s['expired_at']?></td>
</tr>
<?php
}
}
?>
</table>
</td>
<td class="p-0">
<table class="table table-hover table-bordered mb-0">
<tr>
<td>數量</td>
<td>到期日</td>
</tr>
<?php
if ($product['stock']['nearing']['data']) {
foreach ($product['stock']['nearing']['data'] as $s) {
?>
<tr>
<td class="text-right"><?=number_format($s['stock'])?></td>
<td><?=$s['expired_at']?></td>
</tr>
<?php
}
}
?>
</table>
</td>
<td class="p-0">
<table class="table table-hover table-bordered mb-0 border-0">
<tr>
<td>數量</td>
<td>到期日</td>
</tr>
<?php
if ($product['stock']['expired']['data']) {
foreach ($product['stock']['expired']['data'] as $s) {
?>
<tr>
<td class="text-right"><?=number_format($s['stock'])?></td>
<td><?=$s['expired_at']?></td>
</tr>
<?php
}
}
?>
</table>
</td>
<td class="p-0">
<table class="table table-hover table-bordered mb-0">
<tr>
<td>數量</td>
</tr>
<tr>
<td class="text-right"><?=number_format($product['stock']['untag']['total'])?></td>
</tr>
</table>
</td>
</tr>
</table>
</div><file_sep>/application/controllers/Shipment.php
<?php
class Shipment extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
$this->load->model('purchase_model');
$this->load->model('shipment_model');
$this->load->model('shipment_item_model');
$this->load->model('shipment_revise_model');
$this->load->model('shipment_revise_item_model');
$this->load->model('shipment_expiration_model');
$this->load->helper('data_format');
$this->load->library('stock_lib');
$this->session->set_userdata('return_page', base_url('/shipment/overview'));
}
public function overview()
{
$total_shipments_count = $this->shipment_model
->where('ship_type', 'order')
->where('shipin_retailer_id', $this->dealer['retailer_id'])
->count_rows();
$shipments = $this->shipment_model
->with_confirm(['non_exclusive_where' => "confirm_type='shipment'"])
->with_shipout_retailer()
->where('ship_type', 'order')
->where('shipin_retailer_id', $this->dealer['retailer_id'])
->order_by('id', 'desc')
->paginate(20, $total_shipments_count);
//權限設定
$authority = array();
if ($this->authentic->authority('confirm', 'overview')){
$authority['confirm_overview'] = true;
}
if ($this->authentic->authority('shipment', 'confirm')){
$authority['confirm'] = true;
}
if ($this->authentic->authority('shipment', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'shipments' => $shipments,
'pagination' => $this->shipment_model->all_pages,
'authority' => $authority,
'title' => '收貨紀錄列表',
'view' => 'shipment/overview',
];
$this->_preload($data);
}
public function detail($purchase_id)
{
$purchase = $this->purchase_model
->with_transfer_from(['with' => [
['relation' => 'shipin_retailer', 'fields' => 'company,invoice_title'],
['relation' => 'retailer', 'fields' => 'company,invoice_title'],
]
])
->group_start()
->where('retailer_id', $this->dealer['retailer_id'])
->where('shipout_retailer_id', $this->dealer['retailer_id'], null, true)
->group_end()
->get($purchase_id);
if (!$purchase) {
show_error('查無出貨單資料');
}
$ship_data = [
'title' => '進貨單 ' . $purchase['purchaseNum'],
'add' => (!$purchase['isShipped'] && $purchase['shipout_retailer_id'] == $this->dealer['retailer_id']) ? true : false,
'add_url' => base_url('/shipment/add/' . $purchase_id)
];
$total_shipments_count = $this->shipment_model
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->count_rows();
$shipments = $this->shipment_model
->with_confirm(['non_exclusive_where' => "confirm_type='shipment'"])
->with_shipout_retailer()
->with_shipin_retailer()
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->order_by('id', 'desc')
->paginate(20, $total_shipments_count);
//權限設定
$authority = array();
if ($this->authentic->authority('shipment', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('confirm', 'overview')){
$authority['confirm_overview'] = true;
}
if ($this->authentic->authority('shipment', 'confirm')){
$authority['confirm'] = true;
}
if ($this->authentic->authority('shipment', 'cancel')){
$authority['cancel'] = true;
}
$data = [
'purchase' => $purchase,
'ship_data' => $ship_data,
'shipments' => $shipments,
'pagination' => $this->shipment_model->all_pages,
'authority' => $authority,
'title' => '出貨紀錄列表',
'view' => 'shipment/detail',
];
$this->_preload($data);
}
public function add($purchase_id)
{
$purchase = $this->purchase_model
->with_retailer('fields:company')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company')
->with_items()
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase) {
show_error('查無出貨單資料');
}
if (!$purchase['isConfirmed']) {
show_error('此出貨單未確認');
}
if (!$purchase['isPaid']) {
show_error('此出貨單未付款');
}
if ($purchase['isShipped']) {
show_error('此出貨單已出貨');
}
$this->load->model('purchase_item_model');
$items = $this->purchase_item_model
->with_product()
->where('purchase_id', $purchase_id)
->get_all();
if (!$items){
show_error('此出貨單無商品資料');
} else {
$products = [];
foreach ($items as $item){
if (!isset($products[$item['product_id']])){
$stocks = $this->stock_model
->where('product_id', $item['product_id'])
->where('retailer_id', $this->dealer['retailer_id'])
->where('stock', '>', 0)
->group_start()
->where('expired_at', '>=', date('Y-m-d'), true)
->where('expired_at IS NULL', null, null, true, false, true)
->group_end()
->order_by('ISNULL(expired_at)', 'asc')
->order_by('expired_at', 'asc')
->get_all();
$products[$item['product_id']] = [
'name' => $item['product']['pdName'] . $item['product']['intro2'],
'qty' => 0,
'stocks' => $stocks,
];
}
$products[$item['product_id']]['qty'] += $item['qty'];
}
}
$eta_limit = [
'start' => date('Y-m-d', strtotime($purchase['paid_at'])),
'end' => date('Y-m-d', strtotime($purchase['paid_at'].' + ' . $this->dealer['eta_days'] .' days')),
];
if ($this->input->post()) {
$this->form_validation->set_rules('eta_at', '出貨日期', 'required|valid_date');
$this->form_validation->set_rules('fare', '運費', 'required|integer|greater_than_equal_to[0]');
$check_expired_options = [
'products' => $products,
'items' => $this->input->post('items'),
];
$this->form_validation->set_rules('items', '出貨數量', 'callback_check_shipping_qty[' . json_encode($check_expired_options) . ']');
if ($this->form_validation->run() !== FALSE) {
$shipment_id = $this->shipment_model->insert([
'ship_type' => 'purchase',
'ship_id' => $purchase_id,
'shipout_retailer_id' => $purchase['shipout_retailer_id'],
'shipin_retailer_id' => $purchase['retailer_id'],
'eta_at' => $this->input->post('eta_at'),
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->update(['isShipped' => 1, 'shipped_at' => $this->input->post('eta_at')], ['id' => $purchase_id]);
//轉單要再複製一個出貨單
$transfer_purchase = $this->purchase_model
->where('transfer_id', $purchase_id)
->get();
if ($transfer_purchase){
$transfer_shipment_id = $this->shipment_model->insert([
'shipment_id' => $shipment_id,
'ship_type' => 'purchase',
'ship_id' => $transfer_purchase['id'],
'shipout_retailer_id' => $transfer_purchase['shipout_retailer_id'],
'shipin_retailer_id' => $transfer_purchase['retailer_id'],
'eta_at' => $this->input->post('eta_at'),
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->update(['isShipped' => 1, 'shipped_at' => $this->input->post('eta_at')], ['id' => $transfer_purchase['id']]);
}
foreach ($purchase['items'] as $item) {
$this->shipment_item_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
if ($transfer_purchase){
$this->shipment_item_model->insert([
'shipment_id' => $transfer_shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
}
}
//紀錄產品有效期限
$items = (array)$this->input->post('items');
foreach ($items as $product_id => $expired_data) {
foreach ($expired_data as $expired_at => $qty) {
if ($qty > 0) {
$this->shipment_expiration_model->insert([
'shipment_id' => $shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $qty,
]);
if ($transfer_purchase){
$this->shipment_expiration_model->insert([
'shipment_id' => $transfer_shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $qty,
]);
}
}
}
}
//出貨扣庫
$this->stock_lib->shipout_confirm($shipment_id);
//運費
$fare = $this->input->post('fare');
if ($fare > 0) {
$this->load->model('expense_model');
$this->expense_model->insert([
'retailer_id' => $purchase['shipout_retailer_id'],
'event_type' => 'shipment',
'event_id' => $shipment_id,
'expense_type' => 'freight',
'price' => $fare,
'dealer_id' => $this->dealer['id'],
]);
}
redirect(base_url('/transfer/detail/' . $purchase_id));
}
}
$data = [
'eta_limit' => $eta_limit,
'purchase' => $purchase,
'products' => $products,
'title' => '新增出貨紀錄',
'view' => 'shipment/add',
];
$this->_preload($data);
}
public function check_shipping_qty($i, $params)
{
$params = json_decode($params, true);
$products = (array)$params['products'];
$items = (array)$params['items'];
$error = '';
if (!$items) {
$error = '無輸入任何商品';
} else {
foreach ($products as $product_id => $product){
if (!isset($items[$product_id])) {
$error = '輸入的商品未輸入數量';
break;
}
$shipping_qty = 0;
$expired_data = $items[$product_id];
foreach ($expired_data as $expired_at => $qty){
if ($qty > 0) {
$match_stock = false;
foreach ($product['stocks'] as $stock){
if ((is_null($stock['expired_at']) && empty($expired_at)) || $stock['expired_at'] == $expired_at){
if ($stock['stock'] < $qty){
$error = '輸入的商品出貨數量大於有效日之庫存';
break 3;
}
$match_stock = true;
}
}
if (!$match_stock) {
$error = '輸入的商品庫存到期日有誤';
break 2;
}
$shipping_qty += $qty;
}
}
if ($product['qty'] != $shipping_qty){
$error = '輸入的商品訂購數量與出貨總量不符';
break;
}
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_shipping_qty', $error);
return false;
}
}
public function confirm($shipment_id)
{
$shipment = $this->shipment_model
->with_items(['with' => ['relation' => 'product']])
->with_expense(['non_exclusive_where' => "event_type='shipment' AND expense_type='freight'", 'with' => ['relation' => 'retailer', 'fields' => 'company']])
->where('ship_type', 'purchase')
->where('isRevised', 0)
->where('isReturn', 0)
->where('shipin_retailer_id', $this->dealer['retailer_id'])
->get($shipment_id);
if (!$shipment_id || !$shipment) {
show_error('查無收貨資料');
}
if (!is_null($shipment['isConfirmed'])){
show_error('已確認過收貨資料');
}
$purchase = $this->purchase_model
->with_transfer_from()
->with_retailer('fields:company,invoice_title')
->with_shipin_retailer('fields:company,invoice_title')
->with_shipout_retailer('fields:company,invoice_title')
->with_payments(['non_exclusive_where' => "`pay_type`='purchase'", 'with' => ['relation' => 'confirm', 'non_exclusive_where' => "confirm_type='payment'"]])
->with_confirm(['non_exclusive_where' => "confirm_type='purchase'"])
->get($shipment['ship_id']);
if (!$purchase) {
show_error('查無出貨單資料');
}
if (!empty($purchase['transfer_from'])) {
show_error('轉單不能收貨確認');
}
$transfer_shipment = [];
if (!is_null($purchase['transfer_id'])) {
$transfer_shipment = $this->shipment_model
->get($shipment['shipment_id']);
}
$_products = $this->shipment_expiration_model
->where('shipment_id', $shipment_id)
->get_all();
$products = [];
if ($_products){
foreach ($_products as $p){
if (!isset($products[$p['product_id']])){
$products[$p['product_id']] = [];
}
$p['expired_at'] = is_null($p['expired_at']) ? 0 : $p['expired_at'];
$products[$p['product_id']][] = $p;
}
}
if ($this->input->post()) {
$this->form_validation->set_rules('items', '數量', 'callback_check_qty[' . json_encode(['shipment_items' => $shipment['items'], 'products' => $products, 'items' => $this->input->post('items')]) . ']');
if ($this->form_validation->run() !== FALSE) {
$items = (array)$this->input->post('items');
$memo_pictures = empty($_FILES['memo_pictures']) ? [] : $_FILES['memo_pictures'];
$isAllCorrect = true;
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
foreach ($shipment['items'] as $shipment_item) {
$product_id = $shipment_item['product_id'];
foreach ($products[$product_id] as $stock) {
$stock_qty = $stock['qty'];
$shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];
if ($stock_qty != $shipin_qty) {
$isAllCorrect = false;
}
}
}
$this->load->model('confirm_model');
$this->confirm_model->confirmed('shipment', $shipment_id, 1, $this->dealer);
$this->shipment_model->update(['isConfirmed' => 1], ['id' => $shipment_id]);
if ($transfer_shipment) {
$this->confirm_model->confirmed('shipment', $transfer_shipment['id'], 1, $this->dealer);
$this->shipment_model->update(['isConfirmed' => 1], ['id' => $transfer_shipment['id']]);
}
if ($isAllCorrect){
$this->stock_lib->shipin_confirm($shipment_id);
$this->purchase_model->checkCorrect($shipment['ship_id']);
if ($transfer_shipment) {
$this->purchase_model->checkCorrect($transfer_shipment['ship_id']);
}
} else {
$this->purchase_model->update(['isRevised' => 1], ['id' => $shipment['ship_id']]);
$shipment_revise_id = $this->shipment_revise_model->insert([
'shipment_id' => $shipment_id,
'isConfirmed' => 0,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
if ($transfer_shipment) {
$this->purchase_model->update(['isRevised' => 1], ['id' => $transfer_shipment['ship_id']]);
$transfer_shipment_revise_id = $this->shipment_revise_model->insert([
'shipment_id' => $transfer_shipment['id'],
'isConfirmed' => 0,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
}
foreach ($shipment['items'] as $shipment_item) {
$product_id = $shipment_item['product_id'];
foreach ($products[$product_id] as $stock) {
$memo_picture = null;
$shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];
if ($memo_pictures && !empty($memo_pictures['size'][$product_id][$stock['expired_at']])) {
$_FILES['image']['name'] = $memo_pictures['name'][$product_id][$stock['expired_at']];
$_FILES['image']['type'] = $memo_pictures['type'][$product_id][$stock['expired_at']];
$_FILES['image']['tmp_name'] = $memo_pictures['tmp_name'][$product_id][$stock['expired_at']];
$_FILES['image']['error'] = $memo_pictures['error'][$product_id][$stock['expired_at']];
$_FILES['image']['size'] = $memo_pictures['size'][$product_id][$stock['expired_at']];
if ($this->upload->do_upload('image')) {
$upload_data = $this->upload->data();
$memo_picture = '/uploads/' . $upload_data['file_name'];
}
}
$memo = empty($items[$product_id][$stock['expired_at']]['memo']) ? '' : $items[$product_id][$stock['expired_at']]['memo'];
$this->shipment_revise_item_model->insert([
'shipment_revise_id' => $shipment_revise_id,
'product_id' => $product_id,
'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
'qty' => $shipin_qty,
'memo' => $memo,
'memo_file' => $memo_picture,
]);
if ($transfer_shipment) {
$this->shipment_revise_item_model->insert([
'shipment_revise_id' => $transfer_shipment_revise_id,
'product_id' => $product_id,
'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
'qty' => $shipin_qty,
'memo' => $memo,
'memo_file' => $memo_picture,
]);
}
}
}
}
redirect(base_url('/purchase/detail/' . $purchase['id']));
}
}
$this->load->library('purchase_lib');
$purchase_lib = new purchase_lib($purchase);
$purchase['paid_label'] = $purchase_lib->generatePaidLabel(true);
$purchase['confirm_label'] = $purchase_lib->generateConfirmLabel(true);
$purchase['shipped_label'] = $purchase_lib->generateShippedLabel();
$data = [
'purchase' => $purchase,
'shipment' => $shipment,
'products' => $products,
'title' => '確認收貨',
'view' => 'shipment/confirm',
];
$this->_preload($data);
}
public function check_qty($i, $params)
{
$params = json_decode($params, true);
$shipment_items = $params['shipment_items'];
$products = $params['products'];
$items = $params['items'];
$error = '';
foreach ($shipment_items as $shipment_item) {
$product_id = $shipment_item['product_id'];
if (!isset($products[$product_id]) || !isset($items[$product_id])) {
$error = '輸入的貨品錯誤';
break;
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_qty', $error);
return false;
}
}
public function cancel($shipment_id)
{
$shipment = $this->shipment_model
->where('shipout_retailer_id', $this->dealer['retailer_id'])
->get($shipment_id);
if (!$shipment_id || !$shipment) {
show_error('查無出貨資料');
}
if (!is_null($shipment['isConfirmed'])) {
show_error('出貨已經確認不能取消');
}
$purchase = $this->purchase_model
->with_transfer_from()
->get($shipment['ship_id']);
if (!$purchase) {
show_error('查無出貨單資料');
}
//出貨扣庫恢復
$this->stock_lib->shipout_rollback($shipment_id);
$this->shipment_model->delete($shipment_id);
$this->purchase_model->update(['isShipped' => 0, 'shipped_at' => null], ['id' => $purchase['id']]);
if (!empty($purchase['transfer_from'])) {
$transfer_shipment = $this->shipment_model
->where('shipment_id', $shipment_id)
->where('ship_type', 'purchase')
->where('ship_id', $purchase['transfer_from']['id'])
->get();
if ($transfer_shipment) {
$this->shipment_model->delete($transfer_shipment['id']);
$this->purchase_model->update(['isShipped' => 0, 'shipped_at' => null], ['id' => $purchase['transfer_from']['id']]);
}
}
redirect(base_url('/transfer/detail/' . $purchase['id']));
}
public function revise_edit($shipment_revise_id)
{
$shipment_revise = $this->shipment_revise_model
->get($shipment_revise_id);
if (!$shipment_revise_id || !$shipment_revise) {
show_error('查無銷貨異動資料');
}
if ($shipment_revise['isConfirmed']){
show_error('銷貨異動資料已確認');
}
$shipment_id = $shipment_revise['shipment_id'];
$shipment = $this->shipment_model
->with_purchase()
->with_items(['with' => ['relation' => 'product']])
->get($shipment_id);
$transfer_shipment = [];
if (!is_null($shipment['purchase']['transfer_id'])) {
$transfer_shipment = $this->shipment_model
->with_revise()
->get($shipment['shipment_id']);
}
$_products = $this->shipment_expiration_model
->where('shipment_id', $shipment_id)
->get_all();
$products = [];
if ($_products){
foreach ($_products as $p){
if (!isset($products[$p['product_id']])){
$products[$p['product_id']] = [];
}
if (is_null($p['expired_at'])){
$p['expired_at'] = 0;
$this->shipment_revise_item_model->where('expired_at IS NULL', null, null, false, false, true);
} else {
$this->shipment_revise_item_model->where('expired_at', $p['expired_at']);
}
$p['revise'] = $this->shipment_revise_item_model
->where('shipment_revise_id', $shipment_revise_id)
->where('product_id', $p['product_id'])
->get();
$products[$p['product_id']][] = $p;
}
}
if ($this->input->post()) {
$this->form_validation->set_rules('items', '數量', 'callback_check_qty[' . json_encode(['shipment_items' => $shipment['items'], 'products' => $products, 'items' => $this->input->post('items')]) . ']');
if ($this->form_validation->run() !== FALSE) {
$items = (array)$this->input->post('items');
$memo_pictures = empty($_FILES['memo_pictures']) ? [] : $_FILES['memo_pictures'];
$isAllCorrect = true;
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
foreach ($shipment['items'] as $shipment_item) {
$product_id = $shipment_item['product_id'];
foreach ($products[$product_id] as $stock) {
$stock_qty = $stock['qty'];
$shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];
if ($stock_qty != $shipin_qty) {
$isAllCorrect = false;
}
}
}
if ($isAllCorrect){
$this->purchase_model->update(['isRevised' => 0], ['id' => $shipment['ship_id']]);
$this->shipment_revise_model->delete($shipment_revise_id);
$this->stock_lib->shipin_confirm($shipment_id);
$this->purchase_model->checkCorrect($shipment['ship_id']);
if ($transfer_shipment) {
$this->purchase_model->update(['isRevised' => 0], ['id' => $transfer_shipment['ship_id']]);
$this->purchase_model->checkCorrect($transfer_shipment['ship_id']);
}
} else {
$this->shipment_revise_item_model->where('shipment_revise_id', $shipment_revise_id)->delete();
if ($transfer_shipment && !empty($transfer_shipment['revise'])) {
$this->shipment_revise_item_model->where('shipment_revise_id', $transfer_shipment['revise']['id'])->delete();
}
foreach ($shipment['items'] as $shipment_item) {
$product_id = $shipment_item['product_id'];
foreach ($products[$product_id] as $stock) {
$memo_picture = empty($items[$product_id][$stock['expired_at']]['memo_file']) ? null : $items[$product_id][$stock['expired_at']]['memo_file'];
$shipin_qty = $items[$product_id][$stock['expired_at']]['qty'];
if ($memo_pictures && !empty($memo_pictures['size'][$product_id][$stock['expired_at']])) {
$_FILES['image']['name'] = $memo_pictures['name'][$product_id][$stock['expired_at']];
$_FILES['image']['type'] = $memo_pictures['type'][$product_id][$stock['expired_at']];
$_FILES['image']['tmp_name'] = $memo_pictures['tmp_name'][$product_id][$stock['expired_at']];
$_FILES['image']['error'] = $memo_pictures['error'][$product_id][$stock['expired_at']];
$_FILES['image']['size'] = $memo_pictures['size'][$product_id][$stock['expired_at']];
if ($this->upload->do_upload('image')) {
$upload_data = $this->upload->data();
$memo_picture = '/uploads/' . $upload_data['file_name'];
}
}
$memo = empty($items[$product_id][$stock['expired_at']]['memo']) ? '' : $items[$product_id][$stock['expired_at']]['memo'];
$this->shipment_revise_item_model->insert([
'shipment_revise_id' => $shipment_revise_id,
'product_id' => $product_id,
'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
'qty' => $shipin_qty,
'memo' => $memo,
'memo_file' => $memo_picture,
]);
if ($transfer_shipment && !empty($transfer_shipment['revise'])) {
$this->shipment_revise_item_model->insert([
'shipment_revise_id' => $transfer_shipment['revise']['id'],
'product_id' => $product_id,
'expired_at' => $stock['expired_at'] ? $stock['expired_at'] : null,
'qty' => $shipin_qty,
'memo' => $memo,
'memo_file' => $memo_picture,
]);
}
}
}
}
redirect(base_url('/purchase/detail/' . $shipment['ship_id']));
}
}
$data = [
'shipment' => $shipment,
'products' => $products,
'title' => '編輯銷貨異動',
'view' => 'shipment/revise_edit',
];
$this->_preload($data);
}
public function confirm_revise($shipment_revise_id)
{
$shipment_revise = $this->shipment_revise_model
->with_items()
->with_shipment(['with' => ['relation' => 'purchase']])
->get($shipment_revise_id);
if (!$shipment_revise_id || !$shipment_revise) {
show_error('查無銷貨異動資料');
}
if ($shipment_revise['isConfirmed']){
show_error('銷貨異動資料已確認');
}
$shipment_id = $shipment_revise['shipment_id'];
$shipment = $shipment_revise['shipment'];
$purchase = $shipment['purchase'];
$purchase_id = $shipment['ship_id'];
if (!is_null($purchase['transfer_id'])) {
show_error('轉單不能新增銷貨退回');
}
$transfer_shipment = $this->shipment_model
->with_purchase()
->with_revise()
->where('shipment_id', $shipment_id)
->get();
$this->load->model('confirm_model');
$this->confirm_model->confirmed('shipment_revise', $shipment_revise_id, 1, $this->dealer);
$this->shipment_revise_model->update(['isConfirmed' => 1], ['id' => $shipment_revise_id]);
$this->purchase_model->update(['isRevised' => 0], ['id' => $purchase_id]);
$this->purchase_model->checkCorrect($purchase_id);
if ($transfer_shipment && !empty($transfer_shipment['revise'])) {
$this->confirm_model->confirmed('shipment_revise', $transfer_shipment['revise']['id'], 1, $this->dealer);
$this->shipment_revise_model->update(['isConfirmed' => 1], ['id' => $transfer_shipment['revise']['id']]);
$this->purchase_model->update(['isRevised' => 0], ['id' => $transfer_shipment['ship_id']]);
$this->purchase_model->checkCorrect($transfer_shipment['ship_id']);
}
$new_shipment_id = $this->shipment_model->insert([
'shipment_id' => $shipment_id,
'ship_type' => 'purchase',
'ship_id' => $purchase_id,
'shipout_retailer_id' => $shipment['shipout_retailer_id'],
'shipin_retailer_id' => $shipment['shipin_retailer_id'],
'eta_at' => $shipment['eta_at'] ? $shipment['eta_at'] : null,
'memo' => $shipment['memo'] ? $shipment['memo'] : null,
'isConfirmed' => 1,
'isRevised' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
if ($transfer_shipment) {
$new_transfer_shipment_id = $this->shipment_model->insert([
'shipment_id' => $transfer_shipment['id'],
'ship_type' => 'purchase',
'ship_id' => $transfer_shipment['ship_id'],
'shipout_retailer_id' => $transfer_shipment['shipout_retailer_id'],
'shipin_retailer_id' => $transfer_shipment['shipin_retailer_id'],
'eta_at' => $transfer_shipment['eta_at'] ? $transfer_shipment['eta_at'] : null,
'memo' => $transfer_shipment['memo'] ? $transfer_shipment['memo'] : null,
'isConfirmed' => 1,
'isRevised' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
}
foreach ($shipment_revise['items'] as $item) {
$this->shipment_item_model->insert([
'shipment_id' => $new_shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
//紀錄產品有效期限
$this->shipment_expiration_model->insert([
'shipment_id' => $new_shipment_id,
'product_id' => $item['product_id'],
'expired_at' => $item['expired_at'] ? $item['expired_at'] : null,
'qty' => $item['qty'],
]);
if ($transfer_shipment) {
$this->shipment_item_model->insert([
'shipment_id' => $new_transfer_shipment_id,
'product_id' => $item['product_id'],
'qty' => $item['qty'],
]);
$this->shipment_expiration_model->insert([
'shipment_id' => $new_transfer_shipment_id,
'product_id' => $item['product_id'],
'expired_at' => $item['expired_at'] ? $item['expired_at'] : null,
'qty' => $item['qty'],
]);
}
}
//原出貨恢復
$this->stock_lib->shipout_rollback($shipment_id);
//重新出貨扣庫
$this->stock_lib->shipout_confirm($new_shipment_id);
if ($transfer_shipment) {
$this->stock_lib->shipin_confirm($new_transfer_shipment_id);
} else {
$this->stock_lib->shipin_confirm($new_shipment_id);
}
redirect(base_url('/transfer/detail/' . $purchase_id));
}
public function return_add($purchase_id)
{
$purchase = $this->purchase_model
->with_transfer_from()
->where('shipin_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase) {
show_error('查無進貨單資料');
}
if (!$purchase['isShipConfirmed']) {
show_error('進貨單尚未收貨確認');
}
if (!empty($purchase['transfer_from'])) {
show_error('轉單不能新增銷貨退回');
}
$shipment = $this->shipment_model
->with_items(['with' => ['relation' => 'product']])
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->where('isConfirmed', 1)
->order_by('id', 'desc')
->get();
if (!$shipment) {
show_error('查無銷貨單資料');
}
$_products = $this->shipment_expiration_model
->where('shipment_id', $shipment['id'])
->get_all();
$products = [];
if ($_products){
foreach ($_products as $p){
if (!isset($products[$p['product_id']])){
$products[$p['product_id']] = [];
}
$p['expired_at'] = is_null($p['expired_at']) ? 0 : $p['expired_at'];
$products[$p['product_id']][] = $p;
}
}
$shipment_items = [];
if ($shipment['items']){
foreach ($shipment['items'] as $p){
$shipment_items[$p['product_id']] = $p;
}
}
$shipment['items'] = $shipment_items;
if ($this->input->post()) {
$this->form_validation->set_rules('eta_at', '出貨日期', 'required|valid_date');
$this->form_validation->set_rules('fare', '運費', 'required|integer|greater_than_equal_to[0]');
$check_expired_options = [
'shipment_items' => $shipment['items'],
'products' => $products,
'items' => $this->input->post('items'),
];
$this->form_validation->set_rules('items', '出貨數量', 'callback_check_return_qty[' . json_encode($check_expired_options) . ']');
if ($this->form_validation->run() !== FALSE) {
$new_shipment_id = $this->shipment_model->insert([
'ship_type' => 'purchase',
'ship_id' => $purchase_id,
'shipout_retailer_id' => $shipment['shipin_retailer_id'],
'shipin_retailer_id' => $shipment['shipout_retailer_id'],
'eta_at' => $this->input->post('eta_at'),
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'isReturn' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->update(['isReturn' => 1], ['id' => $purchase_id]);
$transfer_purchase = [];
if (!is_null($purchase['transfer_id'])){
$transfer_purchase = $this->purchase_model
->get($purchase['transfer_id']);
if ($transfer_purchase) {
$new_transfer_shipment_id = $this->shipment_model->insert([
'shipment_id' => $new_shipment_id,
'ship_type' => 'purchase',
'ship_id' => $transfer_purchase['id'],
'shipout_retailer_id' => $transfer_purchase['retailer_id'],
'shipin_retailer_id' => $transfer_purchase['shipout_retailer_id'],
'eta_at' => $this->input->post('eta_at'),
'memo' => $this->input->post('memo') ? $this->input->post('memo') : null,
'isReturn' => 1,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
$this->purchase_model->update(['isReturn' => 1], ['id' => $transfer_purchase['id']]);
}
}
$items = (array)$this->input->post('items');
foreach ($items as $product_id => $expired_data) {
$item_qty = 0;
foreach ($expired_data as $expired_at => $qty) {
if ($qty > 0) {
$this->shipment_expiration_model->insert([
'shipment_id' => $new_shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $qty,
]);
if ($transfer_purchase && !empty($new_transfer_shipment_id)) {
$this->shipment_expiration_model->insert([
'shipment_id' => $new_transfer_shipment_id,
'product_id' => $product_id,
'expired_at' => $expired_at ? $expired_at : null,
'qty' => $qty,
]);
}
$item_qty += $qty;
}
}
if ($item_qty > 0) {
$this->shipment_item_model->insert([
'shipment_id' => $new_shipment_id,
'product_id' => $product_id,
'qty' => $item_qty,
]);
if ($transfer_purchase && !empty($new_transfer_shipment_id)) {
$this->shipment_item_model->insert([
'shipment_id' => $new_transfer_shipment_id,
'product_id' => $product_id,
'qty' => $item_qty,
]);
}
}
}
//出貨扣庫
$this->stock_lib->shipout_confirm($new_shipment_id);
//運費
$fare = $this->input->post('fare');
if ($fare > 0) {
$this->load->model('expense_model');
$this->expense_model->insert([
'retailer_id' => $shipment['shipin_retailer_id'],
'event_type' => 'shipment',
'event_id' => $new_shipment_id,
'expense_type' => 'freight',
'price' => $fare,
'dealer_id' => $this->dealer['id'],
]);
}
redirect(base_url('/purchase/detail/' . $purchase_id));
}
}
$data = [
'shipment' => $shipment,
'products' => $products,
'title' => '新增銷貨退回',
'view' => 'shipment/return_add',
];
$this->_preload($data);
}
public function check_return_qty($i, $params)
{
$params = json_decode($params, true);
$shipment_items = (array)$params['shipment_items'];
$products = (array)$params['products'];
$items = (array)$params['items'];
$error = '';
if (!$items) {
$error = '無輸入任何商品';
} else {
foreach ($items as $product_id => $expired_data) {
if (!isset($products[$product_id]) || !isset($shipment_items[$product_id])) {
$error = '輸入的貨品錯誤';
break;
}
$shipping_qty = 0;
foreach ($expired_data as $expired_at => $qty){
if ($qty > 0) {
foreach ($products[$product_id] as $p){
if ($p['expired_at'] == $expired_at){
if ($p['qty'] < $qty){
$error = '銷貨退回商品數量大於原銷貨數量';
break 3;
}
$shipping_qty += $qty;
break;
}
}
}
}
if ($shipment_items[$product_id]['qty'] < $shipping_qty){
$error = '銷貨退回商品總數大於原銷貨總數';
break;
}
}
}
if (!$error) {
return true;
} else {
$this->form_validation->set_message('check_return_qty', $error);
return false;
}
}
public function confirm_return($shipment_id)
{
$shipment = $this->shipment_model
->with_purchase()
->where('ship_type', 'purchase')
->where('isReturn', 1)
->get($shipment_id);
if (!$shipment_id || !$shipment) {
show_error('查無收貨資料');
}
if ($shipment['isConfirmed']){
show_error('已確認過銷貨退回資料');
}
$transfer_shipment = [];
if (!is_null($shipment['purchase']['transfer_id'])) {
show_error('轉單不能新增銷貨退回');
} elseif (!is_null($shipment['shipment_id'])) {
$transfer_shipment = $this->shipment_model
->where('ship_type', 'purchase')
->where('isReturn', 1)
->get($shipment['shipment_id']);
}
$this->load->model('confirm_model');
$this->confirm_model->confirmed('shipment', $shipment_id, 1, $this->dealer);
if ($transfer_shipment) {
$this->confirm_model->confirmed('shipment', $transfer_shipment['id'], 1, $this->dealer);
}
$this->shipment_model->update(['isConfirmed' => 1], ['id' => $shipment_id]);
$this->stock_lib->shipin_confirm($shipment_id);
$this->purchase_model->update(['isReturn' => 0], ['id' => $shipment['ship_id']]);
if ($transfer_shipment) {
$this->shipment_model->update(['isConfirmed' => 1], ['id' => $transfer_shipment['id']]);
$this->purchase_model->update(['isReturn' => 0], ['id' => $transfer_shipment['ship_id']]);
}
redirect(base_url('/transfer/detail/' . $shipment['ship_id']));
}
public function allowance_add($purchase_id)
{
$purchase = $this->purchase_model
->with_transfer_from()
->where('shipin_retailer_id', $this->dealer['retailer_id'])
->get($purchase_id);
if (!$purchase) {
show_error('查無進貨單資料');
}
if (!$purchase['isConfirmed']) {
show_error('進貨單尚未確認');
}
if (!$purchase['isShipConfirmed']) {
show_error('進貨單尚未收貨確認');
}
if (!$purchase['isPayConfirmed']) {
show_error('進貨單尚未確認收款');
}
if (!empty($purchase['transfer_from'])) {
show_error('轉單不能新增銷貨折讓');
}
$shipment = $this->shipment_model
->where('ship_type', 'purchase')
->where('ship_id', $purchase_id)
->where('isConfirmed', 1)
->order_by('id', 'desc')
->get();
if (!$shipment) {
show_error('查無銷貨單資料');
}
if ($this->input->post()) {
$this->form_validation->set_rules('price', '銷貨折讓', 'required|integer|greater_than[0]');
if ($this->form_validation->run() !== FALSE) {
$this->load->model('payment_model');
$this->payment_model->insert([
'pay_type' => 'shipment_allowance',
'pay_id' => $purchase_id,
'paid_retailer_id' => $purchase['shipout_retailer_id'],
'received_retailer_id' => $purchase['retailer_id'],
'price' => $this->input->post('price'),
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
'active' => 0,
]);
$this->purchase_model->update(['isAllowance' => 1], ['id' => $purchase_id]);
if (!is_null($purchase['transfer_id'])){
$transfer_purchase = $this->purchase_model
->get($purchase['transfer_id']);
if ($transfer_purchase) {
$this->payment_model->insert([
'pay_type' => 'shipment_allowance',
'pay_id' => $transfer_purchase['id'],
'paid_retailer_id' => $transfer_purchase['shipout_retailer_id'],
'received_retailer_id' => $transfer_purchase['retailer_id'],
'price' => $this->input->post('price'),
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
'active' => 0,
]);
$this->purchase_model->update(['isAllowance' => 1], ['id' => $transfer_purchase['id']]);
}
}
redirect(base_url('/purchase/detail/' . $purchase_id));
}
}
$data = [
'shipment' => $shipment,
'title' => '新增銷貨折讓',
'view' => 'shipment/allowance_add',
];
$this->_preload($data);
}
}
?><file_sep>/application/libraries/MY_Form_validation.php
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
public function __construct($rules = array())
{
parent::__construct($rules);
}
public function valid_date($str) {
if (($str = strtotime($str)) === FALSE) {
$this->set_message('valid_date', '{field} 欄位必須是一個有效的日期');
return FALSE;
}
return TRUE;
}
//驗證人員帳號是否重複
public function valid_dealer_account($account){
if ($account) {
$this->CI->load->model('dealer_model','',TRUE);
$results = $this->CI->dealer_model
->where('account', strtolower($account))
->get_all();
if (!$results){
return true;
} else {
$this->set_message('valid_dealer_account', '輸入的帳號已曾建立,請新增其他帳號');
return false;
}
} else {
$this->set_message('valid_dealer_account', '必須輸入帳號');
return false;
}
}
//驗證消費者電話是否重複
public function valid_custom_phone($phone, $exclude_id = ''){
if ($phone) {
$this->CI->load->model('customer_model','',TRUE);
$exclude_id = (int)$exclude_id;
if ($exclude_id){
$results = $this->CI->customer_model
->where('phone', $phone)
->where('id', '!=', $exclude_id)
->get_all();
} else {
$results = $this->CI->customer_model
->where('phone', $phone)
->get_all();
}
if (!$results){
return true;
} else {
$this->set_message('valid_custom_phone', '輸入的電話已建立,請新增其他電話');
return false;
}
} else {
$this->set_message('valid_custom_phone', '必須輸入電話');
return false;
}
}
}<file_sep>/application/migrations/052_update_retailer_month_threshold.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_month_threshold extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_retailers', [
'firstThreshold' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
'after' => 'address',
],
'options' => [
'type' => 'TEXT',
'null' => TRUE,
'after' => 'isLocked',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_retailers', 'firstThreshold');
$this->dbforge->drop_column('olive_retailers', 'options');
}
}<file_sep>/application/views/customer/import.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">匯入舊有會員資訊
<div class="float-right">
<a href="<?= base_url('/files/template.xls') ?>" class="btn btn-info mr-2"><i class="fas fa-download"></i> 匯入範本</a>
</div>
</h1>
<form method="post" enctype="multipart/form-data">
<?php if (validation_errors() || $error) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
<?= $error ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">上傳檔案</label>
<input type="file" name="oldfile" required accept="application/vnd.ms-excel" class="form-control-file" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="上傳"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/controllers/Capital_retailer_qualification.php
<?php
class Capital_retailer_qualification extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->helper('data_format');
$this->load->model('retailer_model');
$this->load->model('retailer_level_model');
$this->load->model('retailer_qualification_model');
$this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
}
public function overview($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料!');
}
$total_levels_count = $this->retailer_level_model
->count_rows();
$levels = $this->retailer_level_model
->with_type()
->order_by('retailer_level_type_id', 'asc')
->order_by('code', 'asc')
->paginate(20, $total_levels_count);
if ($levels){
foreach ($levels as $key => $level){
$qualification = $this->retailer_qualification_model
->where('retailer_id', $retailer_id)
->where('retailer_level_id', $level['id'])
->get();
$levels[$key]['qualification'] = empty($qualification) ? 0 : 1;
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('capital_retailer_qualification', 'edit')){
$authority['edit'] = true;
}
$data = [
'retailer' => $retailer,
'levels' => $levels,
'pagination' => $this->retailer_level_model->all_pages,
'authority' => $authority,
'title' => '經銷拓展資格',
'view' => 'capital/retailer/qualification/overview',
];
$this->_preload($data);
}
public function edit($retailer_id, $level_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料!');
}
$level = $this->retailer_level_model
->with_type()
->get($level_id);
if (!$level_id || !$level) {
show_error('查無經銷規則資料');
}
if ($this->input->post()) {
$this->retailer_qualification_model
->where('retailer_id', $retailer_id)
->where('retailer_level_id', $level_id)
->delete();
if ($this->input->post('qualification')){
$this->retailer_qualification_model->insert([
'retailer_id' => $retailer_id,
'retailer_level_id' => $level_id,
]);
}
redirect(base_url('/capital_retailer_qualification/overview/' . $retailer_id));
}
$qualification = $this->retailer_qualification_model
->where('retailer_id', $retailer_id)
->where('retailer_level_id', $level_id)
->get();
$data = [
'retailer' => $retailer,
'level' => $level,
'qualification' => $qualification,
'title' => '編輯經銷拓展資格',
'view' => 'capital/retailer/qualification/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/models/Recommend_template_model.php
<?php
class Recommend_template_model extends MY_Model
{
public $table = 'olive_recommend_templates';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_many['recommends'] = array('Recommend_model', 'recommend_template_id', 'id');
}
}
?>
<file_sep>/application/migrations/032_update_payment.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_payment extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_payments', [
'active' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'memo',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_payments', 'active');
}
}<file_sep>/application/controllers/Confirm.php
<?php
class Confirm extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!$this->dealer = $this->authentic->isLogged()) {
redirect(base_url('/auth/login'));
}
$this->load->model('confirm_model');
$this->load->helper('data_format');
$this->session->set_userdata('return_page', base_url('/confirm/overview'));
}
public function overview($confirm)
{
$confirm_array = explode('_', $confirm);
if (!$confirm_array){
show_error('查無確認資料');
}
$confirm_type = $confirm_array[0];
$confirm_id = $confirm_array[1];
$total_confirms_count = $this->confirm_model
->where('confirm_type', $confirm_type)
->where('confirm_id', $confirm_id)
->count_rows();
if (!$total_confirms_count) {
show_error('查無確認資料');
}
$confirms = $this->confirm_model
->with_retailer()
->where('confirm_type', $confirm_type)
->where('confirm_id', $confirm_id)
->order_by('id', 'desc')
->paginate(20, $total_confirms_count);
$data = [
'confirms' => $confirms,
'pagination' => $this->confirm_model->all_pages,
'title' => '確認紀錄列表',
'view' => 'confirm/overview',
];
$this->_preload($data);
}
}
?><file_sep>/application/migrations/009_add_shipment.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_shipment extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'ship_type' => [
'type' => 'VARCHAR',
'constraint' => 20,
'null' => TRUE,
],
'ship_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'shipout_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'shipin_retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'totalQty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'subtotal' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'total' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'eta_at' => [
'type' => 'date',
'null' => TRUE,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'isConfirmed' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'retailer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'dealer_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_shipments');
}
public function down()
{
$this->dbforge->drop_table('olive_shipments');
}
}<file_sep>/application/migrations/035_update_order.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_order extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_orders', [
'couponNum' => [
'type' => 'VARCHAR',
'constraint' => 30,
'null' => TRUE,
'after' => 'orderNum',
],
'totalDiscount' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
'after' => 'subtotal',
],
'totalReachDiscount' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
'after' => 'totalDiscount',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_orders', 'couponNum');
$this->dbforge->drop_column('olive_orders', 'totalDiscount');
$this->dbforge->drop_column('olive_orders', 'totalReachDiscount');
}
}<file_sep>/application/helpers/data_format_helper.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('confirmStatus')) {
function confirmStatus($key = false, $memo = '', $agree_text='同意', $reject_text='拒絕')
{
if (is_null($key)){
return '<span class="badge badge-light" data-toggle="tooltip" data-html="true" title="' . $memo . '">未確認</span>';
} elseif ($key) {
return '<span class="badge badge-success" data-toggle="tooltip" data-html="true" title="' . $memo . '">' . $agree_text . '</span>';
} else {
return '<span class="badge badge-danger" data-toggle="tooltip" data-html="true" title="' . $memo . '">' . $reject_text . '</span>';
}
}
}
if (!function_exists('eventStatus')) {
function eventStatus($key = false)
{
if ($key) {
return '<span class="badge badge-success">是</span>';
} else {
return '<span class="badge badge-danger">否</span>';
}
}
}
if (!function_exists('yesno')) {
function yesno($key = false)
{
if ($key) {
return '<span class="badge badge-success">是</span>';
} else {
return '<span class="badge badge-danger">否</span>';
}
}
}
if (!function_exists('gender')) {
function gender($key = false)
{
if ($key == '1') {
return '男';
} elseif ($key === '0') {
return '女';
}
return '';
}
}
if (!function_exists('paymentType')) {
function paymentType($key = false)
{
if ($key) {
$key = (int)$key;
switch ($key) {
case 1:
return '現金付款';
break;
case 2:
return '匯款';
break;
default:
return '';
break;
}
} else {
return [
1 => '現金付款',
2 => '匯款',
];
}
}
}
<file_sep>/application/views/shipment/return_add.php
<div class="container">
<h1 class="mb-4">新增銷貨退回</h1>
<form id="returnForm" method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">是否同時寄出商品</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="yesno" id="yesno_1" value="1" required>
<label class="form-check-label" for="yesno_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="yesno" id="yesno_0" value="0">
<label class="form-check-label" for="yesno_0">否</label>
</div>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">出貨日期</label>
<input type="date" name="eta_at" class="form-control"
value="<?= set_value('eta_at', date('Y-m-d')) ?>" required />
</div>
<div class="form-group">
<label class="font-weight-bold">支付運費單位</label>
<div>出貨方</div>
</div>
<div class="form-group">
<label class="font-weight-bold">運費</label>
<input type="number" name="fare" class="form-control text-right"
value="<?= set_value('fare', 0) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">出貨方之備註</label>
<textarea rows="5" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
</div>
<h4 class="my-4 text-center">出貨內容及有效期限</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>貨品名稱</td>
<td>到期日</td>
<td>銷貨數量</td>
<td>退回數量</td>
</tr>
<?php
if ($shipment['items']) {
foreach ($shipment['items'] as $product_id => $shipment_item) {
if (!isset($products[$product_id])){
continue;
}
$product_row = count($products[$product_id]);
?>
<tr>
<td rowspan="<?=$product_row?>" class="align-middle"><?= $shipment_item['product']['pdName'] . $shipment_item['product']['intro2'] ?></td>
<?php
foreach ($products[$product_id] as $key => $product){
if ($key > 0){
echo '</tr><tr>';
}
?>
<td class="align-middle">
<?= $product['expired_at'] ? $product['expired_at'] : '未標示'?>
</td>
<td class="align-middle text-right"><?= number_format($product['qty']) ?></td>
<td class="align-middle">
<input type="number" class="itemQty form-control text-right" name="items[<?=$product_id?>][<?=$product['expired_at']?>]" max="<?=$product['qty']?>" min="0" value="0" />
</td>
<?php
}
?>
</tr>
<?php
}
}
?>
</table>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/purchase/detail/' . $shipment['ship_id']) ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn_submit btn btn-success" value="送出銷貨退回"/>
</div>
</form>
</div>
<script>
$(document).ready(function () {
check_ship();
$('input[name="yesno"]').change(function () {
check_ship();
});
function check_ship() {
if ($('input[name="yesno"]:checked').val() == 1) {
$('.btn_submit').removeClass('d-none');
} else {
$('.btn_submit').addClass('d-none');
}
}
$("#returnForm").submit(function (e) {
if ($('input[name="yesno"]:checked').val() != 1) {
return false;
}
var totalQty = 0;
$('#returnForm input.itemQty').each(function () {
totalQty += parseInt($(this).val()) || 0;
});
if (totalQty == 0) {
alert('請至少退回一樣商品!');
return false;
}
});
});
</script><file_sep>/application/models/Purchase_defect_model.php
<?php
class Purchase_defect_model extends MY_Model
{
public $table = 'olive_purchase_defects';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['purchase'] = array('foreign_model' => 'Purchase_model', 'foreign_table' => 'olive_purchases', 'foreign_key' => 'id', 'local_key' => 'purchase_id');
$this->has_one['item'] = array('foreign_model' => 'Purchase_item_model', 'foreign_table' => 'olive_purchase_items', 'foreign_key' => 'id', 'local_key' => 'purchase_item_id');
$this->has_one['expense'] = array('foreign_model' => 'Expense_model', 'foreign_table' => 'olive_expenses', 'foreign_key' => 'event_id', 'local_key' => 'id');
}
public function getTransferDefect($defect_id, $isTransfer = false)
{
$transfer_purchase_id = '';
if (!$isTransfer) {
$defect = $this
->with_purchase()
->with_item()
->get($defect_id);
if ($defect && $defect['purchase'] && $defect['item'] && !is_null($defect['purchase']['transfer_id'])) {
$transfer_purchase_id = $defect['purchase']['transfer_id'];
$product_id = $defect['item']['product_id'];
}
} else {
$defect = $this
->with_purchase(['with' => ['relation' => 'transfer_from']])
->with_item()
->get($defect_id);
if ($defect && $defect['purchase'] && $defect['item'] && $defect['purchase']['transfer_from']) {
$transfer_purchase_id = $defect['purchase']['transfer_from']['id'];
$product_id = $defect['item']['product_id'];
}
}
if ($transfer_purchase_id) {
$this->load->model('purchase_item_model');
$transfer_purchase_item = $this->purchase_item_model->getPurchaseItemOfId($transfer_purchase_id, $product_id);
if ($transfer_purchase_item && $transfer_purchase_item['defect']) {
return $transfer_purchase_item;
}
}
return false;
}
}
?>
<file_sep>/application/migrations/017_add_commission.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_commission extends CI_Migration
{
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'commission_type' => [
'type' => 'VARCHAR',
'constraint' => 10,
'null' => TRUE,
],
'commission_id' => [
'type' => 'INT',
'unsigned' => TRUE,
'null' => TRUE,
],
'purchase_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'total' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_commissions');
}
public function down()
{
$this->dbforge->drop_table('olive_commissions');
}
}<file_sep>/application/migrations/060_add_shipment_expiration.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_shipment_expiration extends CI_Migration
{
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'shipment_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'expired_at' => [
'type' => 'date',
'null' => TRUE,
],
'qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'created_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'updated_at' => [
'type' => 'timestamp',
'null' => TRUE,
],
'deleted_at' => [
'type' => 'timestamp',
'null' => TRUE,
]
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_shipment_expirations');
}
public function down()
{
$this->dbforge->drop_table('olive_shipment_expirations');
}
}<file_sep>/application/views/capital/customer_level/overview.php
<div class="container">
<h1 class="mb-4">會員資格管理</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">名稱</th>
<th class="text-center">折扣</th>
<th class="text-center">說明</th>
<th></th>
</tr>
<?php
if ($levels) {
foreach ($levels as $level) {
?>
<tr>
<td class="text-center"><?= $level['title'] ?></td>
<td class="text-center"><?= $level['discount'] . '%' ?></td>
<td><?= $level['description'] ?></td>
<td class="text-center">
<?php if (!empty($authority['edit'])){ ?>
<div class="btn-group" role="group">
<a class="btn btn-info btn-sm" href="<?= base_url('/capital_customer_level/edit/' . $level['id']) ?>">編輯</a>
</div>
<?php } ?>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="4" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
</div><file_sep>/application/migrations/034_update_coupon.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_coupon extends CI_Migration
{
public function up()
{
$this->dbforge->drop_column('olive_coupons', 'receive_qty');
$this->dbforge->drop_column('olive_coupons', 'issue_qty');
$this->dbforge->drop_column('olive_coupons', 'approve_qty');
$this->dbforge->add_column('olive_coupons', [
'qty' => [ //領用張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
'after' => 'coupon_month',
],
'first_couponNum' => [
'type' => 'VARCHAR',
'constraint' => 30,
'null' => TRUE,
'after' => 'qty',
],
'last_couponNum' => [
'type' => 'VARCHAR',
'constraint' => 30,
'null' => TRUE,
'after' => 'first_couponNum',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_coupons', 'qty');
$this->dbforge->drop_column('olive_coupons', 'first_couponNum');
$this->dbforge->drop_column('olive_coupons', 'last_couponNum');
$this->dbforge->add_column('olive_coupons', [
'receive_qty' => [ //領用張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
'after' => 'coupon_month',
],
'issue_qty' => [ //發放張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
'after' => 'receive_qty',
],
'approve_qty' => [ //核定張數
'type' => 'INT',
'unsigned' => TRUE,
'default' => 0,
'after' => 'issue_qty',
],
]);
}
}<file_sep>/application/models/Order_return_item_model.php
<?php
class Order_return_item_model extends MY_Model
{
public $table = 'olive_order_return_items';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = false;
$this->soft_deletes = false;
$this->return_as = 'array';
$this->has_one['order_return'] = array('foreign_model' => 'Order_return_model', 'foreign_table' => 'olive_order_returns', 'foreign_key' => 'id', 'local_key' => 'order_return_id');
$this->has_one['product'] = array('foreign_model'=>'Product_model','foreign_table'=>'product','foreign_key'=>'pdId','local_key'=>'product_id');
}
}
?>
<file_sep>/application/views/recommend_template/inside/edit.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">修改定案之推薦函</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label>內容</label>
<textarea class="form-control" name="content" rows="10" required><?= set_value('content', $template['content']) ?></textarea>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/recommend_template/inside')?>" class="btn btn-secondary">不儲存</a>
<input type="submit" class="btn btn-success" value="儲存"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/libraries/Authentic.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Authentic
{
var $CI;
var $dealer = [];
public function __construct()
{
$this->CI =& get_instance();
if ($this->CI->session->userdata('dealer') !== false) {
$dealer_info = $this->CI->session->userdata('dealer');
$this->dealer = $dealer_info;
}
}
public function authenticate($account, $password)
{
$password = $<PASSWORD>($password);
$time = date("Y-m-d H:i:s");
$this->CI->load->model('dealer_model');
$result = $this->CI->dealer_model
->where('account', $account)
->where('password', $password)
->with_retailer(['with' => [['relation' => 'sales_retailer'], ['relation' => 'sales_dealer']]])
->get();
if ($result) {
$level = [];
if (!empty($result['retailer']['retailer_level_id'])) {
$this->CI->load->model('retailer_level_model');
$retailer_level = $this->CI->retailer_level_model
->with_type()
->get($result['retailer']['retailer_level_id']);
$level = [
'discount' => $retailer_level['discount'],
'discount_text' => $retailer_level['discount'] . '%',
'title' => $retailer_level['type']['title'],
'type_id' => $retailer_level['type']['id'],
'type' => $retailer_level['type']['type'],
'code' => $retailer_level['code'],
'firstThreshold' => $retailer_level['firstThreshold'],
'monthThreshold' => $retailer_level['monthThreshold'],
];
//經銷有最低訂購金額,超過一個月沒有超過門檻停用帳號
$this->CI->load->library('purchase_lib');
$dealer_total_purchases = $this->CI->purchase_lib->getRetailerTotalPurchases($result['retailer_id']);
if ($dealer_total_purchases) {
$next_month_first_day = date('Y-m-d', strtotime('first day of next month ' . $dealer_total_purchases['first_at']));
$first_time_month_diff = $this->CI->purchase_lib->get_month_diff($next_month_first_day);
if ($first_time_month_diff > 1 && $retailer_level['monthThreshold'] > ($dealer_total_purchases['total'] - $dealer_total_purchases['first_total'])){ //超過一個月進貨沒有到額度
$now = date('Y-m-d H:i:s');
$this->CI->load->model('retailer_model');
$this->CI->retailer_model->update(['disabled_at' => $now], ['id' => $result['retailer_id']]);
$result['retailer']['disabled_at'] = $now;
}
}
}
$this->dealer = [
'id' => $result['id'],
'retailer_id' => $result['retailer_id'],
'retailer_role_id' => $result['retailer']['retailer_role_id'],
'company' => $result['retailer']['company'],
'invoice_title' => $result['retailer']['invoice_title'],
'identity' => $result['retailer']['identity'],
'contact_dealer_id' => $result['retailer']['contact_dealer_id'],
'contact' => '',
'contactNum' => '',
'phone' => $result['retailer']['phone'],
'altPhone' => $result['retailer']['altPhone'],
'address' => $result['retailer']['address'],
'hasStock' => $result['retailer']['hasStock'],
'totalStock' => $result['retailer']['totalStock'],
'isAllowBulk' => $result['retailer']['isAllowBulk'],
'eta_days' => $result['retailer']['eta_days'],
'disabled' => is_null($result['retailer']['disabled_at']) ? 0 : 1,
'name' => $result['name'],
'retailer_group_id' => $result['retailer_group_id'],
'account' => $result['account'],
'gender' => $result['gender'],
'level' => $level,
'sales_retailer' => $result['retailer']['sales_retailer'], //輔銷單位
'sales_dealer' => $result['retailer']['sales_dealer'], //輔銷人
'retailers' => [],
];
//本單位的聯絡人資料
if ($result['retailer']['contact_dealer_id']) {
$contact_dealer = $this->CI->dealer_model
->get($result['retailer']['contact_dealer_id']);
if ($contact_dealer) {
$this->dealer['contact'] = $contact_dealer['name'];
$this->dealer['contactNum'] = $contact_dealer['account'];
}
}
//取得本單位的下屬單位
$this->CI->load->model('retailer_relationship_model');
$retailers = $this->CI->retailer_relationship_model
->with_retailer()
->where('relation_retailer_id', $this->dealer['retailer_id'])
->where('relation_type', 'supervisor')
->get_all();
if ($retailers) {
foreach ($retailers as $retailer) {
array_push($this->dealer['retailers'], $retailer['id']);
}
}
$this->CI->session->set_userdata('dealer', $this->dealer);
$this->CI->load->model('dealer_history_model');
$this->CI->dealer_history_model
->insert([
'IP' => $this->CI->input->ip_address(),
'stName' => $account,
'LoginTime' => $time,
'stId_link' => $result['id'],
'SID' => $this->CI->session->session_id,
]);
return true;
} else {
$this->CI->load->model('bad_login_model');
$this->CI->bad_login_model
->insert([
'account' => $account,
'ip' => $this->CI->input->ip_address(),
'btime' => $time,
]);
$this->dealer = [];
$this->CI->session->unset_userdata('dealer');
return false;
}
}
public function check_password($password)
{
if ($this->dealer) {
$password = $this->_mix($password);
$this->CI->load->model('dealer_model');
$result = $this->CI->dealer_model
->where('password', $password)
->get($this->dealer['id']);
if ($result) {
return true;
}
}
return false;
}
public function logout()
{
$this->CI->load->model('dealer_history_model');
$dealer_history = $this->CI->dealer_history_model
->where('SID', $this->CI->session->userdata('session_id'))
->order_by('autoid', 'DESC')
->get();
if ($dealer_history) {
$this->CI->dealer_history_model
->update(['LogoutTime' => date("Y-m-d H:i:s")], ['autoid' => $dealer_history['autoid']]);
}
$this->dealer = [];
$this->CI->session->unset_userdata('dealer');
$this->CI->session->unset_userdata('guest');
$this->CI->session->sess_destroy();
}
public function isLogged()
{
return $this->dealer;
}
public function _mix($hash)
{
$hash = md5($hash);
return substr($hash, 10) . substr($hash, 0, 6);
}
public function authority($classname, $methodname = 'index')
{
if (!$classname) {
return false;
}
if (!$this->dealer) {
return false;
}
$this->CI->load->model('privilege_model');
$privileges = $this->CI->privilege_model
->where('classname', $classname)
->get_all();
$privilege_error = true;
if ($privileges) {
foreach ($privileges as $privilege){
if ($privilege['methodname'] == $methodname){
$rules = unserialize($privilege['rules']);
if ($rules) {
if (!empty($rules[$this->dealer['retailer_group_id']])) {
$privilege_error = false;
}
}
break;
}
}
}
if ($privilege_error) {
return false;
} else {
return true;
}
}
}
?><file_sep>/application/migrations/013_add_purchase_item.php
<?php
//經銷商訂貨單產品
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Add_purchase_item extends CI_Migration {
public function up()
{
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'purchase_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'product_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'price' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'subtotal' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'discount' => [
'type' => 'INT',
'constraint' => 3,
'unsigned' => TRUE,
'default' => 100,
],
'total' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_purchase_items');
//缺貨
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'purchase_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'purchase_item_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'supple_qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'isSupple' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'refund' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'isRefund' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'picture' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'import_method' => [
'type' => 'tinyint',
'constraint' => 2,
'unsigned' => TRUE,
'null' => TRUE,
],
'export_response' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_purchase_shortages');
//瑕疵品
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'purchase_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'purchase_item_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'supple_qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'null' => TRUE,
],
'isSupple' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'refund' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'isRefund' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
'memo' => [
'type' => 'TEXT',
'null' => TRUE,
],
'picture' => [
'type' => 'VARCHAR',
'constraint' => 200,
'null' => TRUE,
],
'import_method' => [
'type' => 'tinyint',
'constraint' => 2,
'unsigned' => TRUE,
'null' => TRUE,
],
'export_response' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_purchase_defects');
//退貨
$this->dbforge->add_field([
'id' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'auto_increment' => TRUE
],
'purchase_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'purchase_item_id' => [
'type' => 'INT',
'unsigned' => TRUE,
],
'qty' => [
'type' => 'INT',
'constraint' => 10,
'unsigned' => TRUE,
'default' => 0,
],
'isReturn' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'null' => TRUE,
],
]);
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table('olive_purchase_returns');
}
public function down()
{
$this->dbforge->drop_table('olive_purchase_items');
$this->dbforge->drop_table('olive_purchase_shortages');
$this->dbforge->drop_table('olive_purchase_defects');
$this->dbforge->drop_table('olive_purchase_returns');
}
}<file_sep>/application/models/Retailer_group_model.php
<?php
class Retailer_group_model extends MY_Model
{
public $table = 'olive_retailer_groups';
public $primary_key = 'id';
function __construct()
{
parent::__construct();
$this->timestamps = true;
$this->soft_deletes = true;
$this->return_as = 'array';
$this->has_one['role'] = array('foreign_model' => 'Retailer_role_model', 'foreign_table' => 'olive_retailer_roles', 'foreign_key' => 'id', 'local_key' => 'retailer_role_id');
$this->has_one['level_type'] = array('foreign_model' => 'Retailer_level_type_model', 'foreign_table' => 'olive_retailer_level_types', 'foreign_key' => 'id', 'local_key' => 'retailer_level_type_id');
$this->has_many['dealers'] = array('Dealer_model', 'retailer_group_id', 'id');
}
public function getGroupSelect($retailer_role_id, $retailer_level_type_id = null)
{
if ($retailer_level_type_id){
$this->where('retailer_level_type_id', $retailer_level_type_id);
}
$_groups = $this
->where('retailer_role_id', $retailer_role_id)
->get_all();
$groups = [];
if ($_groups) {
foreach ($_groups as $group) {
$groups[$group['id']] = $group['title'];
}
}
return $groups;
}
}
?>
<file_sep>/application/views/shipment/add.php
<div class="container">
<h1 class="mb-4">新增出貨通知</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">收貨對象</label>
<div><?= $purchase['shipin_retailer']['invoice_title'] ?></div>
</div>
<div class="form-group">
<label class="font-weight-bold">收貨地址</label>
<td>
<?php
echo $purchase['shipin_address'];
if (!$purchase['isMatchBox']){
echo '<div class="text-danger">取貨方式限定親自至輔銷單位取貨</div>';
}
?>
</td>
</div>
<div class="form-group">
<label class="font-weight-bold">是否同時寄出商品</label>
<div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="yesno" id="yesno_1" value="1" required>
<label class="form-check-label" for="yesno_1">是</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="yesno" id="yesno_0" value="0">
<label class="form-check-label" for="yesno_0">否</label>
</div>
</div>
</div>
<div class="form-group">
<label class="font-weight-bold">出貨日期</label>
<input type="date" name="eta_at" class="form-control"
value="<?= set_value('eta_at', $eta_limit['start']) ?>" min="<?= $eta_limit['start'] ?>"
max="<?= $eta_limit['end'] ?>" required/>
<small class="text-mute">出貨期限為<?= $eta_limit['end'] ?></small>
</div>
<div class="form-group">
<label class="font-weight-bold">支付運費單位</label>
<div>出貨方</div>
</div>
<div class="form-group">
<label class="font-weight-bold">運費</label>
<input type="number" name="fare" class="form-control text-right"
value="<?= set_value('fare', 0) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">出貨方之備註</label>
<textarea rows="5" name="memo" class="form-control"><?= set_value('memo') ?></textarea>
</div>
<h4 class="my-4 text-center">出貨內容及有效期限</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>貨品名稱</td>
<td>訂購數量</td>
<td>庫存到期日</td>
<td>庫存數量</td>
<td>出貨數量</td>
</tr>
<?php
if ($products) {
foreach ($products as $product_id => $product) {
$stock_row = count($product['stocks']);
?>
<tr>
<td rowspan="<?=$stock_row?>" class="align-middle"><?= $product['name'] ?></td>
<td rowspan="<?=$stock_row?>" class="align-middle text-right"><?= number_format($product['qty']) ?></td>
<?php if (empty($product['stocks'])){ ?>
<td class="align-middle"></td>
<td class="align-middle">無庫存</td>
<td class="align-middle text-danger item_shortage">庫存數量不足以出貨</td>
<?php
} else {
$product_qty = $product['qty'];
foreach ($product['stocks'] as $k => $stock) {
$qty = min($product_qty, $stock['stock']);
if ($k > 0){
echo '</tr><tr>';
}
?>
<td class="align-middle"><?= $stock['expired_at'] ? $stock['expired_at'] : '未標示' ?></td>
<td class="align-middle text-right"><?= number_format($stock['stock']) ?></td>
<td class="align-middle">
<input type="number" class="form-control text-right" name="items[<?=$product_id?>][<?=$stock['expired_at']?>]" max="<?=$product['qty']?>" min="0" value="<?=$qty?>" />
</td>
<?php
if ($product_qty == $qty) {
$product_qty = 0;
} else {
$product_qty -= $qty;
}
}
}
?>
</tr>
<?php
}
}
?>
</table>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/transfer/detail/' . $purchase['id']) ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn_submit btn btn-success" value="送出已出貨訊息"/>
</div>
</form>
</div>
<script>
$(document).ready(function () {
showSubmit();
$('input[name="yesno"]').change(function () {
showSubmit();
});
function showSubmit() {
var checkShip = check_ship();
var checkShortage = check_shortage();
if (checkShip && checkShortage){
$('.btn_submit').removeClass('d-none');
} else {
$('.btn_submit').addClass('d-none');
}
}
function check_ship() {
if ($('input[name="yesno"]:checked').val() == 1) {
return true;
} else {
return false;
}
}
function check_shortage() {
if ($('.item_shortage').length > 0){
return false;
} else {
return true;
}
}
$("#purchaseForm").submit(function (e) {
if ($('input[name="yesno"]:checked').val() != 1) {
return false;
}
});
});
</script><file_sep>/application/controllers/Stock_counting.php
<?php
class Stock_counting extends MY_Controller
{
protected $dealer, $counting_reason;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || !$this->dealer['hasStock']) {
redirect(base_url('/'));
}
$this->load->model('stock_model');
$this->load->model('stock_counting_model');
$this->load->model('product_model');
$this->counting_reason = [
'M' => '月盤點',
'P' => '總部不定期季盤點',
'E' => '其他事由',
];
$this->session->set_userdata('return_page', base_url('/stock_counting/index'));
}
public function index()
{
//權限設定
$authority = array();
if ($this->authentic->authority('stock_counting', 'set_print')){
$authority['print'] = true;
}
if ($this->authentic->authority('stock_counting', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('stock_counting', 'overview')){
$authority['overview'] = true;
}
$data = [
'authority' => $authority,
'title' => '盤點作業',
'view' => 'stock_counting/index',
];
$this->_preload($data);
}
public function set_print()
{
$products = $this->product_model->getUnitProductStocks($this->dealer['retailer_id']);
//權限設定
$authority = array();
if ($this->authentic->authority('stock_counting', 'process_print')){
$authority['print'] = true;
}
$data = [
'counting_reason' => $this->counting_reason,
'products' => $products,
'authority' => $authority,
'title' => '「盤點清冊」下載',
'view' => 'stock_counting/set_print',
];
$this->_preload($data);
}
public function process_print()
{
$counting_reason = $this->input->get('counting_reason');
if (!$counting_reason || !in_array($counting_reason, array_keys($this->counting_reason))){
show_error('盤點事由未填寫');
}
$products = $this->product_model->getUnitProductStocks($this->dealer['retailer_id']);
$data = [
'counting_reason' => $this->counting_reason[$counting_reason],
'products' => $products,
'title' => '列印「盤點清冊」',
'view' => 'stock_counting/process_print',
];
$this->_preload($data);
}
public function overview()
{
$total_countings_count = $this->stock_counting_model
->where('retailer_id', $this->dealer['retailer_id'])
->where('isConfirmed', 1)
->count_rows();
$stock_countings = $this->stock_counting_model
->with_dealer(['with' => ['relation' => 'trashed']])
->where('retailer_id', $this->dealer['retailer_id'])
->where('isConfirmed', 1)
->order_by('id', 'desc')
->paginate(20, $total_countings_count);
//權限設定
$authority = array();
if ($this->authentic->authority('stock_counting', 'detail')){
$authority['detail'] = true;
}
if ($this->authentic->authority('stock_counting', 'edit')){
$authority['edit'] = true;
}
$data = [
'counting_reason' => $this->counting_reason,
'stock_countings' => $stock_countings,
'pagination' => $this->stock_counting_model->all_pages,
'authority' => $authority,
'title' => '盤點歷史紀錄列表',
'view' => 'stock_counting/overview',
];
$this->_preload($data);
}
public function detail($stock_counting_id)
{
$stock_counting = $this->stock_counting_model
->with_items(['with' => ['relation' => 'product', 'with' => ['relation' => 'product_kind', 'fields' => 'ctName']]])
->where('retailer_id', $this->dealer['retailer_id'])
->where('isConfirmed', 1)
->get($stock_counting_id);
if (!$stock_counting_id || !$stock_counting) {
show_error('查無盤點歷史紀錄');
}
$data = [
'counting_reason' => $this->counting_reason,
'stock_counting' => $stock_counting,
'title' => '盤盈虧報表',
'view' => 'stock_counting/detail',
];
$this->_preload($data);
}
public function add()
{
$error = '';
if ($this->input->post()) {
$counting_reason = $this->input->post('counting_reason');
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
if ($_FILES['description_file'] && $_FILES['description_file']['size']) {
if ($this->upload->do_upload('description_file')) {
$upload_data = $this->upload->data();
$description_file = '/uploads/' . $upload_data['file_name'];
} else {
$error[] = strip_tags($this->upload->display_errors());
}
} else {
$error[] = '上傳已簽名之盤點表至電腦中指定資料夾';
}
if (!$counting_reason || !in_array($counting_reason, array_keys($this->counting_reason))){
$error[] = '請選擇盤點事由';
}
if (!$error) {
$serialNum = $this->stock_counting_model->getNextSerialNum($counting_reason);
$stock_counting_id = $this->stock_counting_model->insert([
'serialNum' => $serialNum,
'countingNum' => $counting_reason.date('Ymd').$serialNum,
'counting_reason' => $counting_reason,
'description_file' => $description_file,
'retailer_id' => $this->dealer['retailer_id'],
'dealer_id' => $this->dealer['id'],
]);
redirect(base_url('/stock_counting/edit/' . $stock_counting_id));
}
}
$data = [
'error' => $error,
'counting_reason' => $this->counting_reason,
'title' => '盤盈虧報表新增',
'view' => 'stock_counting/add',
];
$this->_preload($data);
}
public function edit($stock_counting_id)
{
$stock_counting = $this->stock_counting_model
->where('retailer_id', $this->dealer['retailer_id'])
->get($stock_counting_id);
if (!$stock_counting_id || !$stock_counting) {
show_error('查無盤點歷史紀錄');
}
$this->load->model('product_model');
$products = $this->product_model->getUnitProductStocks($this->dealer['retailer_id']);
if (!$products) {
show_error('查無產品資料');
}
$this->load->model('stock_counting_item_model');
$diff_reasons = [
'' => '',
1 => '外展區陳列',
2 => '其他',
];
if ($this->input->post()) {
if ($_POST['submit_save']) {
$items = (array)$this->input->post('items');
$diff_files = $_FILES['diff_files'];
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 10000000; //10M
$config['file_ext_tolower'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$this->load->library('stock_lib');
foreach ($items as $product_id => $item) {
foreach ($item as $k => $stock) {
$qty = (int)$stock['qty'];
if (!empty($stock['date']) && strtotime($stock['date']) > 0) {
$date = date('Y-m-d', strtotime($stock['date']));
} else {
$date = null;
}
$diff_reason = empty($stock['diff_reason']) ? 0 : (int)$stock['diff_reason'];
$diff_file = null;
if (!empty($diff_files['size'][$product_id][$k])) {
$_FILES['image']['name'] = $diff_files['name'][$product_id][$k];
$_FILES['image']['type'] = $diff_files['type'][$product_id][$k];
$_FILES['image']['tmp_name'] = $diff_files['tmp_name'][$product_id][$k];
$_FILES['image']['error'] = $diff_files['error'][$product_id][$k];
$_FILES['image']['size'] = $diff_files['size'][$product_id][$k];
if ($this->upload->do_upload('image')) {
$upload_data = $this->upload->data();
$diff_file = '/uploads/' . $upload_data['file_name'];
}
}
$diff_reason_text = null;
if ($diff_reason) {
if ($diff_reason == 3) {
if ($stock['diff_reason_text']) {
$diff_reason_text = $stock['diff_reason_text'];
}
} else {
$diff_reason_text = $diff_reasons[$diff_reason];
}
}
$old_stock = 0;
if ($products[$product_id]['stocks']){
foreach ($products[$product_id]['stocks'] as $s){
if ($s['expired_at'] == $date){
$old_stock += $s['stock'];
}
}
}
$this->stock_counting_item_model->insert([
'stock_counting_id' => $stock_counting_id,
'product_id' => $product_id,
'old_stock' => $old_stock,
'stock' => $qty,
'expired_at' => $date,
'diff_reason' => $diff_reason_text,
'diff_file' => $diff_file,
]);
$this->stock_lib->retailer_stock_value($this->dealer['retailer_id'], $product_id, $qty, $date);
}
}
$this->stock_counting_model->update([
'isConfirmed' => 1,
], ['id' => $stock_counting_id]);
} else { //不儲存
$this->stock_counting_model->delete($stock_counting_id);
}
redirect(base_url('/stock_counting/overview'));
}
$stock_counting_items = $this->stock_counting_item_model
->where('stock_counting_id', $stock_counting_id)
->get_all();
if ($stock_counting_items){
foreach ($stock_counting_items as $item){
$this->stock_counting_item_model->delete($item['id']);
}
}
$data = [
'diff_reason' => $diff_reasons,
'counting_reason' => $this->counting_reason[$stock_counting['counting_reason']],
'stock_counting' => $stock_counting,
'products' => $products,
'title' => '盤盈虧報表編輯',
'view' => 'stock_counting/edit',
];
$this->_preload($data);
}
}
?><file_sep>/application/views/capital/retailer/qualification/overview.php
<div class="container">
<h1 class="mb-4"><?= $retailer['company'] ?>經銷拓展資格</h1>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center">類別</th>
<th class="text-center">代碼</th>
<th class="text-center">名稱</th>
<th class="text-center">折扣</th>
<th class="text-center">首次進貨門檻</th>
<th class="text-center">每月進貨門檻</th>
<th class="text-center">拓展資格</th>
<th></th>
</tr>
<?php
if ($levels) {
foreach ($levels as $level) {
?>
<tr>
<td class="text-center"><?= $level['type']['type'] ?></td>
<td class="text-center"><?= $level['code'] ?></td>
<td class="text-center"><?= $level['type']['title'] ?></td>
<td class="text-center"><?= $level['discount'] . '%' ?></td>
<td class="text-right"><?= $level['firstThreshold'] ? '$'.number_format($level['firstThreshold']) : '' ?></td>
<td class="text-right"><?= $level['monthThreshold'] ? '$'.number_format($level['monthThreshold']) : '' ?></td>
<td class="text-center"><?= yesno($level['qualification']) ?></td>
<td class="text-center">
<?php if (!empty($authority['edit'])){ ?>
<div class="btn-group" role="group">
<a class="btn btn-info btn-sm" href="<?= base_url('/capital_retailer_qualification/edit/' . $retailer['id'] . '/' . $level['id']) ?>">編輯</a>
</div>
<?php } ?>
</td>
</tr>
<?php
}
} else {
?>
<tr>
<td colspan="7" class="text-center">查無資料</td>
</tr>
<?php
}
?>
</table>
<?= $pagination ?>
</div><file_sep>/application/config/setting.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['app_title'] = '貨物管理系統 Ver 1.0';
<file_sep>/application/views/stock_counting/add.php
<div class="container">
<h1 class="mb-4 text-center">盤盈虧報表新增</h1>
<form method="post" enctype="multipart/form-data">
<?php if ($error) { ?>
<div class="alert alert-danger">
<?= implode('<br>', $error) ?>
</div>
<?php } ?>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">盤點事由</label>
<div class="col-sm-10">
<?php
echo form_dropdown('counting_reason', $counting_reason, '', 'class="form-control" required');
?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">承辦人</label>
<div class="col-sm-10">
<?= $dealer['name'] ?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 form-check-label font-weight-bold">上傳已簽名之盤點表至電腦中指定資料夾</label>
<div class="col-sm-10">
<input type="file" class="form-control-file" id="description_file" name="description_file" required />
</div>
</div>
<div class="form-group text-center">
<input type="submit" class="btn btn-success" value="產生「庫存列表」" />
</div>
</form>
</div><file_sep>/application/controllers/Capital_retailer.php
<?php
class Capital_retailer extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('retailer_model');
$this->load->model('dealer_model');
$this->session->set_userdata('return_page', base_url('/capital_retailer/overview'));
}
public function overview()
{
$total_retailers_count = $this->retailer_model
->count_rows();
$retailers = $this->retailer_model
->with_role()
->with_contact_dealer()
->with_level(['with' => ['relation' => 'type']])
->order_by('id', 'desc')
->paginate(20, $total_retailers_count);
//權限設定
$authority = array();
if ($this->authentic->authority('capital_retailer', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_retailer', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_retailer', 'cancel')){
$authority['cancel'] = true;
}
if ($this->authentic->authority('capital_dealer', 'overview')){
$authority['dealer'] = true;
}
if ($this->authentic->authority('capital_retailer_qualification', 'overview')){
$authority['qualification'] = true;
}
if ($this->authentic->authority('capital_relationship_shipout', 'overview')){
$authority['shipout'] = true;
}
if ($this->authentic->authority('capital_relationship_shipin', 'overview')){
$authority['shipin'] = true;
}
if ($this->authentic->authority('capital_relationship_invoice', 'overview')){
$authority['invoice'] = true;
}
if ($this->authentic->authority('capital_relationship_invoice_send', 'overview')){
$authority['invoice_send'] = true;
}
if ($this->authentic->authority('capital_relationship_visor', 'overview')){
$authority['supervisor'] = true;
}
$data = [
'retailers' => $retailers,
'pagination' => $this->retailer_model->all_pages,
'authority' => $authority,
'title' => '單位總覽',
'view' => 'capital/retailer/overview',
];
$this->load->helper('data_format');
$this->_preload($data);
}
public function add()
{
$this->load->model('retailer_role_model');
$roles = $this->retailer_role_model->getRoleSelect();
$retailer_selects = $this->retailer_model->getRetailerSelect();
$dealer_selects = $this->dealer_model->getDealerSelect();
if ($this->input->post()) {
$this->form_validation->set_rules('retailer_role_id', '單位類型', 'required|integer|in_list[' . implode(',',array_keys($roles)) . ']');
$this->form_validation->set_rules('sales_retailer_id', '輔銷單位', 'integer|in_list[' . implode(',',array_keys($retailer_selects)) . ']');
$this->form_validation->set_rules('sales_dealer_id', '輔銷人', 'integer|in_list[' . implode(',',array_keys($dealer_selects)) . ']');
$this->form_validation->set_rules('company', '單位名稱', 'required|max_length[20]');
$this->form_validation->set_rules('invoice_title', '單位抬頭', 'max_length[20]');
$this->form_validation->set_rules('identity', '統一編號', 'required|max_length[10]');
$this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
$this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
$this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
$this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('purchaseThreshold', '每月進貨門檻', 'integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('hasStock', '管理庫存', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('totalStock', '總倉庫存', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('isAllowBulk', '散裝進貨資格', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('eta_days', '出貨期限', 'integer');
$this->form_validation->set_rules('bank', '收款銀行', 'max_length[100]');
$this->form_validation->set_rules('bank_branch', '分行名', 'max_length[100]');
$this->form_validation->set_rules('bank_account_title', '收款戶名', 'max_length[100]');
$this->form_validation->set_rules('bank_account', '收款帳戶', 'max_length[100]');
if ($this->form_validation->run() !== FALSE) {
$retailer_role_id = $this->input->post('retailer_role_id');
$this->retailer_model->insert([
'sales_retailer_id' => $this->input->post('sales_retailer_id') ? $this->input->post('sales_retailer_id') : null,
'sales_dealer_id' => $this->input->post('sales_dealer_id') ? $this->input->post('sales_dealer_id') : null,
'retailer_role_id' => $retailer_role_id,
'company' => $this->input->post('company'),
'invoice_title' => $this->input->post('invoice_title') ? $this->input->post('invoice_title') : null,
'bank' => $this->input->post('bank') ? $this->input->post('bank') : null,
'bank_branch' => $this->input->post('bank_branch') ? $this->input->post('bank_branch') : null,
'bank_account_title' => $this->input->post('bank_account_title') ? $this->input->post('bank_account_title') : null,
'bank_account' => $this->input->post('bank_account') ? $this->input->post('bank_account') : null,
'identity' => $this->input->post('identity'),
'phone' => $this->input->post('phone'),
'altPhone' => $this->input->post('altPhone'),
'address' => $this->input->post('address'),
'firstThreshold' => ($this->input->post('firstThreshold') >= 0) ? $this->input->post('firstThreshold') : null,
'purchaseThreshold' => ($this->input->post('purchaseThreshold') >= 0) ? $this->input->post('purchaseThreshold') : null,
'hasStock' => $this->input->post('hasStock'),
'totalStock' => $this->input->post('totalStock'),
'isAllowBulk' => $this->input->post('isAllowBulk'),
'eta_days' => $this->input->post('eta_days') ? $this->input->post('eta_days') : null,
]);
redirect(base_url('/capital_retailer/overview/'));
}
}
$this->load->helper('form');
$data = [
'roles' => $roles,
'retailer_selects' => $retailer_selects,
'dealer_selects' => $dealer_selects,
'title' => '新增經銷單位',
'view' => 'capital/retailer/add',
];
$this->_preload($data);
}
public function edit($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料');
}
$retailer_selects = $this->retailer_model->getRetailerSelect();
$dealer_selects = $this->dealer_model->getDealerSelect();
$this->load->model('dealer_model');
$dealers = $this->dealer_model->getDealerSelect($retailer_id);
if ($this->input->post()) {
$this->form_validation->set_rules('sales_retailer_id', '輔銷單位', 'integer|in_list[' . implode(',',array_keys($retailer_selects)) . ']');
$this->form_validation->set_rules('sales_dealer_id', '輔銷人', 'integer|in_list[' . implode(',',array_keys($dealer_selects)) . ']');
$this->form_validation->set_rules('company', '單位名稱', 'required|max_length[20]');
$this->form_validation->set_rules('invoice_title', '單位抬頭', 'max_length[20]');
$this->form_validation->set_rules('identity', '統一編號', 'required|max_length[10]');
$this->form_validation->set_rules('contact_dealer_id', '單位代表人', 'integer|in_list[' . implode(',',array_keys($dealers)) . ']');
$this->form_validation->set_rules('phone', '聯絡電話1', 'required|is_natural|max_length[20]');
$this->form_validation->set_rules('altPhone', '聯絡電話2', 'is_natural|max_length[20]');
$this->form_validation->set_rules('address', '聯絡地址', 'required|max_length[100]');
$this->form_validation->set_rules('firstThreshold', '首次進貨門檻', 'integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('purchaseThreshold', '每月進貨門檻', 'integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('hasStock', '管理庫存', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('totalStock', '總倉庫存', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('isAllowBulk', '散裝進貨資格', 'required|integer|in_list[0,1]');
$this->form_validation->set_rules('eta_days', '出貨期限', 'integer');
$this->form_validation->set_rules('bank', '收款銀行', 'max_length[100]');
$this->form_validation->set_rules('bank_branch', '分行名', 'max_length[100]');
$this->form_validation->set_rules('bank_account_title', '收款戶名', 'max_length[100]');
$this->form_validation->set_rules('bank_account', '收款帳戶', 'max_length[100]');
if ($this->form_validation->run() !== FALSE) {
$this->retailer_model->update([
'sales_retailer_id' => $this->input->post('sales_retailer_id') ? $this->input->post('sales_retailer_id') : null,
'sales_dealer_id' => $this->input->post('sales_dealer_id') ? $this->input->post('sales_dealer_id') : null,
'company' => $this->input->post('company'),
'invoice_title' => $this->input->post('invoice_title') ? $this->input->post('invoice_title') : null,
'bank' => $this->input->post('bank') ? $this->input->post('bank') : null,
'bank_branch' => $this->input->post('bank_branch') ? $this->input->post('bank_branch') : null,
'bank_account_title' => $this->input->post('bank_account_title') ? $this->input->post('bank_account_title') : null,
'bank_account' => $this->input->post('bank_account') ? $this->input->post('bank_account') : null,
'identity' => $this->input->post('identity'),
'contact_dealer_id' => $this->input->post('contact_dealer_id') ? $this->input->post('contact_dealer_id') : null,
'phone' => $this->input->post('phone'),
'altPhone' => $this->input->post('altPhone'),
'address' => $this->input->post('address'),
'firstThreshold' => ($this->input->post('firstThreshold') >= 0) ? $this->input->post('firstThreshold') : null,
'purchaseThreshold' => ($this->input->post('purchaseThreshold') >= 0) ? $this->input->post('purchaseThreshold') : null,
'hasStock' => $this->input->post('hasStock'),
'totalStock' => $this->input->post('totalStock'),
'isAllowBulk' => $this->input->post('isAllowBulk'),
'eta_days' => $this->input->post('eta_days') ? $this->input->post('eta_days') : null,
], ['id' => $retailer_id]);
redirect(base_url('/capital_retailer/overview/'));
}
}
$data = [
'dealers' => $dealers,
'retailer' => $retailer,
'retailer_selects' => $retailer_selects,
'dealer_selects' => $dealer_selects,
'title' => '編輯經銷單位',
'view' => 'capital/retailer/edit',
];
$this->_preload($data);
}
public function cancel($retailer_id)
{
$retailer = $this->retailer_model
->get($retailer_id);
if (!$retailer_id || !$retailer) {
show_error('查無經銷單位資料');
}
if ($retailer['isLocked']){
show_error('預設經銷單位不能刪除');
}
$this->retailer_model->delete($retailer_id);
redirect(base_url('/capital_retailer/overview/'));
}
}
?><file_sep>/application/views/consumer/order-return.php
<div class="container">
<div class="row justify-content-md-center">
<div class="col-md-8">
<h1 class="mb-4">貨到付款退貨作業</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<h4 class="my-4 text-center">已收之退貨內容物</h4>
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<td>項次</td>
<td>貨品編號</td>
<td>貨品名稱</td>
<td>單價</td>
<td>訂購數量</td>
<td>金額小計</td>
<td>折扣</td>
<td>折扣價</td>
</tr>
<?php
if ($items) {
$i = 1;
foreach ($items as $item) {
?>
<tr>
<td data-th="項次" class="text-center"><?= $i ?></td>
<td data-th="貨品編號"><?= $item['product']['p_num'] ?></td>
<td data-th="貨品名稱"><?= $item['product']['pdName'] ?> <?= $item['product']['intro2'] ?></td>
<td data-th="單價" class="text-right">$<?= number_format($item['price']) ?></td>
<td data-th="訂購數量" class="text-right"><?= number_format($item['qty']) ?></td>
<td data-th="金額小計" class="text-right">$<?= number_format($item['price'] * $item['qty']) ?></td>
<td data-th="折扣" class="text-right"><?= $item['discount'] . '%'?></td>
<td data-th="折扣價" class="text-right">$<?= number_format($item['subPrice']) ?></td>
</tr>
<?php
$i++;
}
}
?>
</table>
<div class="form-group">
<label class="font-weight-bold">已付之退貨運費</label>
<input type="number" name="freight" class="form-control text-right"
value="<?= set_value('freight', 0) ?>" required/>
</div>
<div class="form-group">
<label class="font-weight-bold">已付之退貨手續費</label>
<input type="number" name="fare" class="form-control text-right"
value="<?= set_value('fare', 0) ?>" required/>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?=base_url('/consumer/payAtShipped')?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn btn-success" value="退貨完成"/>
</div>
</form>
</div>
</div>
</div><file_sep>/application/views/supervisor/info.php
<div class="container">
<h1 class="mb-4"><?= $retailer['company'] ?>經銷單位基本資料</h1>
<p class="card-text">經銷商類別: <?= $retailer['level_title'] ?></p>
<p class="card-text">加入經銷商日期: <?= date('Y/m/d', strtotime($retailer['created_at'])) ?></p>
<p class="card-text">身份證字號/統一編號: <?= $retailer['identity'] ?></p>
<p class="card-text">聯絡電話1: <?= $retailer['phone'] ?></p>
<p class="card-text">聯絡電話2: <?= $retailer['altPhone'] ?></p>
<p class="card-text">送貨地址: <?= $retailer['address'] ?></p>
<?php if (!empty($retailer['sales_retailer'])) { ?>
<p class="card-text">輔銷單位: <?= $retailer['sales_retailer']['company'] ?></p>
<?php } ?>
<?php if (!empty($retailer['sales_dealer'])) { ?>
<p class="card-text">輔銷人: <?= $retailer['sales_dealer']['name'] ?></p>
<?php } ?>
<?php if (!empty($retailer['contact_dealer'])){
?>
<p class="card-text">主要聯絡人帳號: <?= $retailer['contact_dealer']['account'] ?></p>
<p class="card-text">主要聯絡人名字: <?= $retailer['contact_dealer']['name'] ?></p>
<p class="card-text">主要聯絡人性別: <?= $retailer['contact_dealer']['gender'] ? '男' : '女' ?></p>
<?php
}
?>
</div><file_sep>/application/views/stock_counting/set_print.php
<div class="container">
<div class="float-right">盤點日期: <?=date('Y/m/d')?></div>
<h1 class="mb-4"><?= $dealer['company'] ?>庫存列表</h1>
<form method="get" action="<?=base_url('/stock_counting/process_print')?>">
<table class="table table-hover table-bordered table-responsive-sm">
<tr>
<th class="text-center" style="width: 5%;">項次</th>
<th class="text-center" style="width: 25%;">貨品編號</th>
<th class="text-center" style="width: 28%;">貨品名稱</th>
<th class="text-center" style="width: 8%;">到期日</th>
<th class="text-center" style="width: 8%;">庫存數量</th>
<th class="text-center" style="width: 16%;">盤點量</th>
<th class="text-center">盤差說明</th>
</tr>
<?php
if ($products) {
$i = 1;
foreach ($products as $product_id => $product) {
$stocks_row = count($product['stocks']);
?>
<tr<?= ($product['pKind'] == '3') ? ' class="olive_bg"' : '' ?>>
<td class="text-center" rowspan="<?=$stocks_row?>"><?= $i ?></td>
<td class="text-center" rowspan="<?=$stocks_row?>"><?= $product['p_num'] ?></td>
<td class="text-center" rowspan="<?=$stocks_row?>"><?= $product['pdName'] ?> <?= $product['intro2'] ?></td>
<?php
if (!empty($product['stocks'][0])){
?>
<td><?=$product['stocks'][0]['expired_at']?></td>
<td class="text-right"><?=$product['stocks'][0]['stock']?></td>
<?php
} else {
?>
<td></td>
<td class="text-right">0</td>
<?php
}
?>
<td class="text-right" rowspan="<?=$stocks_row?>"></td>
<td class="text-right" rowspan="<?=$stocks_row?>"></td>
</tr>
<?php
if ($stocks_row > 1){
foreach ($product['stocks'] as $k => $s) {
if ($k) {
?>
<tr>
<td><?=$s['expired_at']?></td>
<td class="text-right"><?=$s['stock']?></td>
</tr>
<?php
}
}
}
?>
<?php
$i++;
}
}
?>
<tr>
<td colspan="2">
<label>盤點事由:</label>
<?php
echo form_dropdown('counting_reason', $counting_reason, '', 'class="form-control"');
?>
</td>
<td colspan="2">
<h3>陪同人:<span class="text-mute">請簽名</span></h3>
</td>
<td colspan="2">
<h3>盤點人:<span class="text-mute">請簽名</span></h3>
</td>
</tr>
</table>
<?php if (!empty($authority['print'])){ ?>
<div class="text-center my-4">
<button type="submit" class="btn btn-success">列印</button>
</div>
<?php } ?>
</form>
</div><file_sep>/application/migrations/067_update_retailer_allow_bulk.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Update_retailer_allow_bulk extends CI_Migration
{
public function up()
{
$this->dbforge->add_column('olive_retailers', [
'isAllowBulk' => [
'type' => 'tinyint',
'constraint' => 1,
'unsigned' => TRUE,
'default' => 0,
'after' => 'isLocked',
],
]);
}
public function down()
{
$this->dbforge->drop_column('olive_retailers', 'isAllowBulk');
}
}<file_sep>/application/controllers/Capital_product.php
<?php
class Capital_product extends MY_Controller
{
protected $dealer;
public function __construct()
{
parent::__construct();
if (!($this->dealer = $this->authentic->isLogged()) || $this->dealer['retailer_role_id'] != 2) {
redirect(base_url('/'));
}
$this->load->model('product_model');
$this->session->set_userdata('return_page', base_url('/capital_product/overview'));
}
public function overview()
{
$total_products_count = $this->product_model
->count_rows();
$products = $this->product_model
->with_product_kind()
->with_pao()
->where('pKind', [3,6])
->where('pEnable', 'Y')
->order_by('pKind', 'asc')
->order_by('pdId', 'asc')
->paginate(20, $total_products_count);
//進貨商品管理
$this->load->model('retailer_model');
$this->load->model('product_permission_model');
$retailer_selects = $this->retailer_model->getRetailerSelect();
$_permissions = $this->product_permission_model->get_all();
$permissions = [];
if ($_permissions){
foreach ($_permissions as $k => $p){
$retailers = [];
$_retailers = is_null($p['include_retailers']) ? null : explode(',', $p['include_retailers']);
if ($_retailers){
foreach ($_retailers as $retailer_id){
$retailers[] = $retailer_selects[$retailer_id];
}
}
$p['retailers'] = $retailers;
$permissions[$p['product_id']] = $p;
}
}
//權限設定
$authority = array();
if ($this->authentic->authority('capital_product', 'add')){
$authority['add'] = true;
}
if ($this->authentic->authority('capital_product', 'edit')){
$authority['edit'] = true;
}
if ($this->authentic->authority('capital_product', 'cancel')){
$authority['cancel'] = true;
}
if ($this->authentic->authority('capital_product_permission', 'edit')){
$authority['permission'] = true;
}
if ($this->authentic->authority('capital_product_pao', 'overview')){
$authority['pao'] = true;
}
$data = [
'products' => $products,
'permissions' => $permissions,
'pagination' => $this->product_model->all_pages,
'authority' => $authority,
'title' => '商品總覽',
'view' => 'capital/product/overview',
];
$this->_preload($data);
}
public function add()
{
$this->load->model('product_kind_model');
$kind_selects = $this->product_kind_model->getKindSelect();
$this->load->model('pao_model');
$pao_selects = $this->pao_model->getPaoSelect();
if ($this->input->post()) {
$this->form_validation->set_rules('p_num', '貨品編號', 'required|max_length[20]');
$this->form_validation->set_rules('pdName', '名稱', 'required|max_length[50]');
$this->form_validation->set_rules('intro2', '外緣尺寸', 'required|max_length[100]');
$this->form_validation->set_rules('pdCash', '單價', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('pKind', '分類', 'required|integer|in_list[' . implode(',',array_keys($kind_selects)) . ']');
$this->form_validation->set_rules('boxAmount', '每箱數量', 'required|integer|greater_than_equal_to[1]');
$this->form_validation->set_rules('pao_id', '有限期限', 'integer|in_list[' . implode(',',array_keys($pao_selects)) . ']');
if ($this->form_validation->run() !== FALSE) {
$this->product_model->insert([
'p_num' => $this->input->post('p_num'),
'pdName' => $this->input->post('pdName'),
'intro2' => $this->input->post('intro2'),
'pdCash' => $this->input->post('pdCash'),
'pKind' => $this->input->post('pKind'),
'boxAmount' => $this->input->post('boxAmount'),
'pao_id' => $this->input->post('pao_id') ? $this->input->post('pao_id') : null,
'pEnable' => 'Y',
'pUpdateDate' => date('Y-m-d H:i:s'),
'pdCosts' => null, //有採購系統計算了
'inStock' => 0, //已經另外存放庫存
'sort_order' => 10, //不知道要幹嘛的
'pUpdateStId_link' => 1, //不知道要幹嘛的
]);
redirect(base_url('/capital_product/overview/'));
}
}
$this->load->helper('form');
$data = [
'kind_selects' => $kind_selects,
'pao_selects' => $pao_selects,
'title' => '新增商品',
'view' => 'capital/product/add',
];
$this->_preload($data);
}
public function edit($product_id)
{
$product = $this->product_model
->get($product_id);
if (!$product_id || !$product) {
show_error('查無商品資料');
}
$this->load->model('product_kind_model');
$kind_selects = $this->product_kind_model->getKindSelect();
$this->load->model('pao_model');
$pao_selects = $this->pao_model->getPaoSelect();
if ($this->input->post()) {
$this->form_validation->set_rules('p_num', '貨品編號', 'required|max_length[20]');
$this->form_validation->set_rules('pdName', '名稱', 'required|max_length[50]');
$this->form_validation->set_rules('intro2', '外緣尺寸', 'required|max_length[100]');
$this->form_validation->set_rules('pdCash', '單價', 'required|integer|greater_than_equal_to[0]');
$this->form_validation->set_rules('pKind', '分類', 'required|integer|in_list[' . implode(',',array_keys($kind_selects)) . ']');
$this->form_validation->set_rules('boxAmount', '每箱數量', 'required|integer|greater_than_equal_to[1]');
$this->form_validation->set_rules('pao_id', '有限期限', 'integer|in_list[' . implode(',',array_keys($pao_selects)) . ']');
if ($this->form_validation->run() !== FALSE) {
$this->product_model->update([
'p_num' => $this->input->post('p_num'),
'pdName' => $this->input->post('pdName'),
'intro2' => $this->input->post('intro2'),
'pdCash' => $this->input->post('pdCash'),
'pKind' => $this->input->post('pKind'),
'boxAmount' => $this->input->post('boxAmount'),
'pao_id' => $this->input->post('pao_id') ? $this->input->post('pao_id') : null,
'pUpdateDate' => date('Y-m-d H:i:s'),
], ['pdId' => $product_id]);
redirect(base_url('/capital_product/overview/'));
}
}
$data = [
'kind_selects' => $kind_selects,
'pao_selects' => $pao_selects,
'product' => $product,
'title' => '編輯商品',
'view' => 'capital/product/edit',
];
$this->_preload($data);
}
public function cancel($product_id)
{
$product = $this->product_model
->get($product_id);
if (!$product_id || !$product) {
show_error('查無經銷商品資料');
}
$this->product_model->update([
'pEnable' => 'N',
], ['pdId' => $product_id]);
redirect(base_url('/capital_product/overview/'));
}
}
?><file_sep>/application/views/shipment/allowance_add.php
<div class="container">
<h1 class="mb-4">新增銷貨折讓</h1>
<form method="post">
<?php if (validation_errors()) { ?>
<div class="alert alert-danger">
<?= validation_errors() ?>
</div>
<?php } ?>
<div class="form-group">
<label class="font-weight-bold">折讓金額</label>
<input type="number" name="price" class="form-control text-right" min="1"
value="<?= set_value('price', 0) ?>" required/>
</div>
<div class="form-group d-flex justify-content-between">
<a href="<?= base_url('/purchase/detail/' . $shipment['ship_id']) ?>" class="btn btn-secondary">取消</a>
<input type="submit" class="btn_submit btn btn-success" value="送出銷貨折讓"/>
</div>
</form>
</div> | 38aad7c4e34e9671d4569fa5ce8f7a92cf9eb85b | [
"Markdown",
"PHP"
] | 241 | PHP | zccmark/pcart | 6a097669bcd42c2f37343037835ed3ba3891cf22 | 23a5bad96f4b1f615269088247793ed06a33bfc0 | |
refs/heads/master | <repo_name>Deivbid/BlogComputacion<file_sep>/BlogComputacion/venv/bin/django-admin.py
#!/home/david/Documentos/ProyectoCAL/BlogComputacion/BlogComputacion/venv/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| c45a718168d9817bc9848a90d6da1e76fba55667 | [
"Python"
] | 1 | Python | Deivbid/BlogComputacion | 56a9ab3c5f57dcc1621e40a70ecd055c0fb213a3 | 6f168e98dbcd5bbab8e9f3ab1201b78349db90c6 | |
refs/heads/master | <repo_name>jochumb/screenplay-pattern-test<file_sep>/src/test/java/nl/jochumborger/test/web/questions/TheCurrentUser.java
package nl.jochumborger.test.web.questions;
import net.serenitybdd.screenplay.Question;
/**
* Created by jochum on 08/07/16.
*/
public class TheCurrentUser {
public static Question<String> username() { return new Username(); }
public static Question<String> twitterHandle() { return new TwitterHandle(); }
}
<file_sep>/src/test/java/nl/jochumborger/test/features/login/LoginStory.java
package nl.jochumborger.test.features.login;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import net.thucydides.core.annotations.Managed;
import net.thucydides.core.annotations.Steps;
import nl.jochumborger.test.twitter.User;
import nl.jochumborger.test.web.questions.TheCurrentUser;
import nl.jochumborger.test.web.tasks.Login;
import nl.jochumborger.test.web.tasks.Logout;
import nl.jochumborger.test.web.tasks.OpenTwitter;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import static net.serenitybdd.screenplay.EventualConsequence.eventually;
import static net.serenitybdd.screenplay.GivenWhenThen.*;
import static org.hamcrest.Matchers.containsString;
/**
* Created by jochum on 08/07/16.
*/
@RunWith(SerenityRunner.class)
public class LoginStory {
User twitterUser = User.getInstance();
Actor lexie = Actor.named("Lexie");
@Managed(uniqueSession = true)
public WebDriver herBrowser;
@Steps
OpenTwitter openTwitter;
@Steps
Logout logout;
@Before
public void lexieCanBrowseTheWeb() {
lexie.can(BrowseTheWeb.with(herBrowser));
}
@Test
public void log_in_with_correct_credentials_should_show_twitter_feed() {
givenThat(lexie).wasAbleTo(openTwitter);
when(lexie).attemptsTo(Login.withCredentials(twitterUser.getUsername(),twitterUser.getPassword()));
then(lexie).should(
eventually(seeThat(TheCurrentUser.username(), containsString(twitterUser.getDisplayName()))),
seeThat(TheCurrentUser.twitterHandle(), containsString(twitterUser.getHandle()))
);
}
@After
public void logout() {
lexie.attemptsTo(logout);
}
}
<file_sep>/src/test/java/nl/jochumborger/test/web/questions/TwitterHandle.java
package nl.jochumborger.test.web.questions;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import nl.jochumborger.test.web.ui.UserInformation;
/**
* Created by jochum on 08/07/16.
*/
public class TwitterHandle implements Question<String> {
@Override
public String answeredBy(Actor actor) {
return Text.of(UserInformation.TWITTER_HANDLE).viewedBy(actor).asString();
}
}
<file_sep>/src/test/java/nl/jochumborger/test/web/ui/UserInformation.java
package nl.jochumborger.test.web.ui;
import net.serenitybdd.screenplay.targets.Target;
import org.openqa.selenium.By;
/**
* Created by jochum on 08/07/16.
*/
public class UserInformation {
public static Target USERNAME = Target.the("twitter username").located(By.cssSelector(".DashboardProfileCard-name a"));
public static Target TWITTER_HANDLE = Target.the("twitter handle").located(By.cssSelector(".DashboardProfileCard-screenname a span"));
}
<file_sep>/src/test/java/nl/jochumborger/test/web/ui/UserMenu.java
package nl.jochumborger.test.web.ui;
import net.serenitybdd.screenplay.targets.Target;
import org.openqa.selenium.By;
/**
* Created by jochum on 08/07/16.
*/
public class UserMenu {
public static Target MENU_DROPDOWN = Target.the("menu dropdown button").located(By.cssSelector("a.dropdown-toggle"));
public static Target LOGOUT = Target.the("logout link").located(By.cssSelector("#signout-button button"));
}
<file_sep>/src/test/java/nl/jochumborger/test/twitter/User.java
package nl.jochumborger.test.twitter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by jochum on 11/07/16.
*/
public class User {
private Properties props;
private static User instance;
private User() {
this.props = new Properties();
try {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("twitter.properties");
this.props.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static User getInstance() {
if (instance == null) {
instance = new User();
}
return instance;
}
public String getUsername() {
return props.getProperty("twitter.username");
}
public String getPassword() {
return props.getProperty("twitter.password");
}
public String getDisplayName() {
return props.getProperty("twitter.displayname");
}
public String getHandle() {
return props.getProperty("twitter.handle");
}
}
<file_sep>/src/test/java/nl/jochumborger/test/features/search/SearchStory.java
package nl.jochumborger.test.features.search;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.screenplay.Actor;
import net.thucydides.core.annotations.Steps;
import nl.jochumborger.test.api.abilities.UseTheApi;
import nl.jochumborger.test.api.tasks.ConnectToTwitter;
import nl.jochumborger.test.api.questions.NumberOfResults;
import nl.jochumborger.test.api.tasks.Search;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static net.serenitybdd.screenplay.GivenWhenThen.*;
import static org.hamcrest.Matchers.greaterThan;
/**
* Created by jochum on 08/07/16.
*/
@RunWith(SerenityRunner.class)
public class SearchStory {
Actor lexie = Actor.named("Lexie");
@Steps
ConnectToTwitter connectToTwitter;
@Before
public void lexieCanUseTheApi() {
lexie.can(UseTheApi.withDefaultContext());
}
@Test
public void search_twitter_via_api_should_contain_expected_results() {
givenThat(lexie).wasAbleTo(connectToTwitter);
when(lexie).attemptsTo(Search.forText("#test"));
then(lexie).should(seeThat(NumberOfResults.count(), greaterThan(0))); //assumption that "#test" is regularly used
}
}
<file_sep>/src/test/java/nl/jochumborger/test/api/exceptions/ActorCannotUseTheApiException.java
package nl.jochumborger.test.api.exceptions;
/**
* Created by jochum on 11/07/16.
*/
public class ActorCannotUseTheApiException extends RuntimeException {
public ActorCannotUseTheApiException(String name) {
super(name);
}
}
<file_sep>/README.md
# Screenplay Pattern test
Experimenting with Screenplay pattern in Serenity, testing simple Twitter functionality
## Project setup
The features folder contrains two stories implemented using the screenplay pattern.
1. Login
* Uses the serenity-screenplay-webdriver module, has most of seleniums features covered
* Classes in the web directory
2. Search
* Uses the twitter API and the serenity-screenplay module, needs some code to bind the two
* Classes in the api directory
## Configure
Rename twitter.properties.example and twitter4j.properties.example (delete .example) and fill with valid values.
## Run
mvn verify
| a41de879d24291c34187208c6e8310576027af2c | [
"Markdown",
"Java"
] | 9 | Java | jochumb/screenplay-pattern-test | bd3c5b686dcbfcd3ea63e1ad1a12e37d1f6251a3 | 7cc4dea7a2400a414162c16e000863f7bcf40e79 | |
refs/heads/master | <file_sep>const EntitySchema = require("typeorm").EntitySchema; // import {EntitySchema} from "typeorm";
const counterModel = require("../model/counter");
module.exports = new EntitySchema({
name :"counter",
target:counterModel,
columns:{
_id:{
primary :true,
type:"varchar",
objectId:true
},
sequence_val:{
type:"int"
}
}
})<file_sep>const EntitySchema = require("typeorm").EntitySchema; // import {EntitySchema} from "typeorm";
const AuthProviderModel = require("../model/AuthProviders");
//const { O } = require("typeorm");
module.exports = new EntitySchema({
name: "AuthProvider",
target: AuthProviderModel,
columns: {
providerId:
{
primary: true,
type: "int",
objectId:true
},
providerName
: {
type: "varchar",
},
createdDate: {
type: "datetime"
}
}
})<file_sep>const EntitySchema = require("typeorm").EntitySchema; // import {EntitySchema} from "typeorm";
const AuthProviderDetailsModel = require("../model/AuthProviderDetails");
const UserDetailsModel = require("../model/UserDetailsModel");
const AuthProviderModel = require("../model/AuthProviders");
module.exports = new EntitySchema({
name: "AuthProviderDetails",
target: AuthProviderDetailsModel,
columns: {
name
: {
type: "varchar"
},
email: {
type: "varchar"
},
createdDate:{
type:"datetime"
},
relations:{
authProviderUserId:
{
target: UserDetailsModel,
type: "one-to-one",
joinTable: true,
cascade: true
},
providerId:
{
target: AuthProviderModel,
type: "one-to-one",
joinTable: true,
cascade: true
},
}
}
})<file_sep>const registerUser = require("../database").registerUser;
module.exports = async (req, res) => {
try{
const user = await registerUser.findUser(req.params.authId);
let response = {};
if(user.length === 0){
response.status = true;
response.data = "User ";
}
else{
response.status = true;
response.data = user[0];
}
res.json(response);
}
catch(ex){
console.log(ex);
res.json({
status: false,
message: "Internal Server Error"
});
}
};
<file_sep>const express = require("express");
const app = express();
const env = require("./config/env_variables").getEnv();
const registerUser = require("./database");
const controllers = require("./controllers");
const amqpStacker = require("./utils/RabbitMQ");
const DBConnection = require("./utils/DBConnection");
app.set('trust proxy')
require("./express-middlewares")(app);
app.post("/user/v1/register", controllers.register.v1);
app.post("/user/v1/login", controllers.login.v1);
app.get("/user/v1/profile", controllers.profile.v1);
process.on('uncaughtException', function (err) {
console.log(err.message);
console.log(err.stack);
});
app.use((req, res, next) => {
res.json({
data: `${req.originalUrl} not found`
});
});
(async () => {
try {
// await registerUser.connect(env.mongodb.url, env.mongodb.dbName);
//console.log(DBConnection);
await amqpStacker.config(env.rabbitmq.server);
app.listen(env.port, () => console.log("Registration Services started at port %s", env.port));
}
catch (ex) {
console.log(`\nError starting the service\n`);
console.log(ex);
process.exit(0);
}
})()
<file_sep>const EntitySchema = require("typeorm").EntitySchema; // import {EntitySchema} from "typeorm";
const UserDetailsModel = require("../model/UserDetailsModel");
const AccountTypeModel = require("../model/AccountType");
module.exports = new EntitySchema({
name: UserDetailsModel,
target: UserDetailsModel,
columns: {
authProviderUserId: {
primary: true,
generated: true,
type: "int"
},
attributeName: {
type: "varchar"
},
acccountStatus: {
type: "varchar"
},
privacy: { type: "varchar" },
termsCondition: { type: "varchar" },
createdDate: { type: "varchar" },
updateDate: { type: "varchar" }
},
relations: {
accountTypeId: {
target: AccountTypeModel,
type: "many-to-one",
joinTable: true,
cascade: true
},
}
})<file_sep>const dbConnection = require("../utils/DBConnection");
const UserDetailsModel = require("../model/UserDetailsModel");
const AuthProviderModel = require("../model/AuthProviders");
const AuthProviderDetailsModel = require("../model/AuthProviderDetails");
const AccountTypeModel = require("../model/AccountType");
const counterModel = require("../model/counter");
const AuthProviderEntity = require("../entity/AuthProviders");
const { getMongoManager, getManager, getMongoRepository, getConnection } = require("typeorm");
class USerDetailRepo {
// manager = getManager();
//This function is used to insert a record of different auth provider like fb,google,linkedin
async createAuthProvider(authProviderName) {
try {
//console.log(dbConnection);
let authProviderSeqVal = this.getNextSequenceValue("authProviderSeq");
console.log("seq val ", authProviderSeqVal);
let authProviderObj = new AuthProviderModel();
authProviderObj.providerId = authProviderSeqVal;
authProviderObj.providerName = authProviderName;
authProviderObj.createdDate = new Date();
const manager = getManager();
await manager.save(authProviderObj);
} catch (ex) {
console.log(ex)
}
}
async findAuthProvider(name) {
try {
console.log("findAuthProvider");
const manager = getManager();
const authProvider = await manager.find(AuthProviderModel, { providerName: name });
//console.log(authProvider);
return authProvider;
} catch (ex) {
console.log(ex);
}
}
async findAccountType(accountName) {
try {
console.log("findAuthProvider");
const manager = getManager();
const accountType = await manager.find(AccountTypeModel, { accountTypeName: accountName });
//console.log(authProvider);
return accountType;
} catch (ex) {
console.log(ex);
}
}
async saveUserAuthProviderDetails(userAuthProvidserData, authProviderId) {
try {
const userAuthProviderDetails = new AuthProviderDetailsModel();
userAuthProviderDetails.authProviderId = authProviderId;
userAuthProviderDetails.authProviderUserId = userAuthProvidserData.authProviderUserId;
userAuthProviderDetails.name = userAuthProvidserData.name;
userAuthProviderDetails.email = userAuthProvidserData.email;
userAuthProviderDetails.createdDate = new Date();
const manager = getManager();
await manager.save(userAuthProviderDetails);
} catch (ex) {
console.log(ex);
}
}
async saveUserDetails() {
try {
const userDetails = new UserDetailsModel(userDetailsData);
userDetails.authProviderUserId = parseInt(authProviderUserId),
userDetails.accountTypeId = userDetailsData.accountTypeId,
userDetails.attributeName = userDetailsData.attributeName,
userDetails.acccountStatus = userDetailsData.acccountStatus,
userDetails.privacy = userDetailsData.privacy,
userDetails.termsCondition = userDetailsData.termsCondition,
userDetails.createdDate = userDetailsData.createdDate,
userDetails.updateDate = userDetailsData.updateDate
const manager = getManager();
await manager.save(userDetails);
} catch (ex) {
console.log(ex);
}
}
async getNextSequenceValue(sequenceName) {
const manager = getMongoManager();
console.log("seqname ", sequenceName);
var seqdocument = await manager.find(counterModel, { _id: sequenceName });
console.log(seqdocument[0]);
var seqVal = seqdocument[0];
// console.log(seqVal);
console.log(seqVal.sequence_val);
var oldSeq = seqVal.sequence_val;
var incSeq = oldSeq + 1;
//let counterObj = new counterModel();
//counterObj._id = sequenceName;
//counterObj.sequence_val = incSeq;
console.log("new seq", incSeq);
var updateSeq = await manager.updateOne(counterModel,{_id:sequenceName}, { '$set': {sequence_val : incSeq }});
var updatedSeqVal = updateSeq[0];
console.log(updatedSeqVal);
return updateSeq[0].sequence_value;
}
}
module.exports = new USerDetailRepo();
<file_sep>class AuthProviders {
constructor(providerId, name,createdDate) {
this.providerId = providerId,
this.providerName = name,
this.createdDate = createdDate
}
}
module.exports = AuthProviders;<file_sep>const registerUser = require("../../database");
const amqp = require("./amqp");
const logger = require("../../config/logger");
const uuidv4 = require('uuid/v4');
const env = require("../../config/env_variables").getEnv();
module.exports = async (req, res) => {
const requestId = uuidv4();
try {
logger.info(`/login ${req.method} requestId: ${requestId}`);
const { accessToken, signedRequest, authProvider } = req.body;
const correlationId = uuidv4();
let userAuthData = null;
if (authProvider === "facebook") {
logger.info(`${requestId}: Request FBServices_Authentication`);
userAuthData = await amqp.FBServices_Authentication({ accessToken, signedRequest }, correlationId, requestId);
logger.info(`${requestId}: User ${userAuthData.id} authenticated by facebook services`);
}
if (userAuthData === null) {
res.json({
data: "No scheme exists to authenticate validate user"
});
return void (0);
}
else {
logger.info(`${requestId}__${userAuthData.id} Request StellarServices_CreateAccount`);
await registerUser.findUser(userAuthData.id);
logger.info(`${requestId}__${userAuthData.id} Sending response to client`);
res.json({
data: "User logged in stacker"
});
}
}
catch (ex) {
console.log(ex);
let error = "";
if (ex.type && ex.type === "Facebook") {
const msg = typeof ex.message === "object" ? JSON.stringify(ex.message) : ex.message;
logger.info(`${requestId}: Facebook Services error, ${msg}`);
error = msg;
}
res.json({
messgae: error
});
}
};
<file_sep>const typeorm = require("typeorm"); // import * as typeorm from "typeorm";
const env = require("../config/env_variables").getEnv();
module.exports = typeorm.createConnection({
type: "mongodb",
host: "localhost",
port: 27017,
//username: "test",
// password: "<PASSWORD>",
database: "StackerUsers",
//synchronize: true,
// logging: false,
entities: [
require("../entity/AuthProviders"),
require("../entity/AccountType"),
require("../entity/counter")
// require("../entity/AuthProviderDetails"),
// require("../entity/UserDetails")
],
useNewUrlParser: true
}).then(function (connection) {
console.log(" DB Connected !!!! ");
return connection
}).catch(function (error) {
console.log("Error: ", error);
});<file_sep>class counter {
constructor(_id, sequence_val) {
this._id = _id,
this.sequence_val = sequence_val
}
}
module.exports = counter;<file_sep>### User Registration Process
The user registration process can be summarised as follows:
<file_sep>class AuthProviderDetails {
constructor(authProviderUserid, name, email, authproviderIdcreatedDate) {
this.authProviderUserId = authProviderUserid,
this.providerId = id,
this.providerName = name,
this.email = email,
this.createdDate = authproviderIdcreatedDate
}
}
module.exports = AuthProviderDetails;<file_sep>exports.register = require("./register");
exports.login = require("./login");
exports.profile = require("./profile");<file_sep>exports.MongoError = (userId, operation, message) => {
throw {
user: userId,
timestamp: Date.now(),
operation: operation,
error_code: message.code,
error_message: message.errmsg
}
};<file_sep>module.exports = (app) => (...middlewares) => ({
get: (routePath, controller) => {
app.get(
routePath,
(req, res, next) => {
middlewares.forEach(mw => mw(req, res, next))
},
controller
)
},
post: (routePath, controller) => {
app.post(
routePath,
(req, res, next) => {
middlewares.forEach(mw => mw(req, res, next))
},
controller
)
}
});<file_sep>const registerUser = require("../../database");
const logger = require("../../config/logger");
const amqp = require("./amqp");
const uuidv4 = require('uuid/v4');
module.exports = async (req, res) => {
const requestId = uuidv4();
logger.info(`/profile ${req.method} requestId: ${requestId}`);
try{
const { userId } = req.query;
const correlationId = uuidv4();
logger.info(`${requestId}__${userId}: Find user in stacker database`);
const user = await registerUser.findUser(userId);
logger.info(`${requestId}: Request StellarServices_Balance`);
const balance = await amqp.StellarServices_Balance({ account: user.account }, correlationId, requestId);
console.log(balance);
logger.info(`${requestId}__${userId} Sending response to client`);
res.json({
name: user.name,
email: user.email,
account_type: user.accountType,
locked: false,
active: true,
balance: {
free: balance.EKRFREE ? balance.EKRFREE : "0",
postpaid: balance.EKR ? balance.EKR : "0"
}
});
}
catch(ex){
console.log(ex);
res
.status(500)
.send("Request Failed");
}
};<file_sep>const registerUser = require("../src/database").registerUser;
const stackerAmqp = require("../src/message-queue/amqp-stacker");
const handleFreeTokens = (_err, _data) => {
if (data1 === "Transferred Tokens") {
await registerUser.changeAccountStatus({
userId,
accountStatus: "Completed"
});
//Calling email Services
stackerAmqp.addEmailDataInQueue({ name: userData.name, email: userData.email, userRegistration:true,freeTokens:10 })
res.json({
status: true,
Result: "User registered"
});
}
};
const handleCreateAccount = async (_err, _data) => {
userData.name, async (err, data) => {
const stellarAccount = JSON.parse(data);
await registerUser.updateStellarAccount({
userId,
account: stellarAccount.account,
encryptedMnemonic: stellarAccount.mnemonic
});
stackerAmqp.sendFreeToken(data, handleFreeTokens);
}
}
const handleFacebookResponse = async (_err, _data) => {
const queueData = JSON.parse(data);
userData = queueData.data;
if(queueData.error === null){
console.log(`\nRegister Services`);
const user = await registerUser.addUser({ userId: userData.id, name: userData.name, email: userData.email });
console.log(`User registered in DB`);
console.log(user);
stackerAmqp.createAccount(handleCreateAccount);
}
else{
console.log(`Error from Facebook Auth Services`);
console.log(queueData.error);
res.json({
status: false,
message: "Error authenticating user"
});
}
};
module.exports = async (req, res) => {
const { userId, name, email, inputAccessToken } = req.body;
try {
const message = {
fbUID: userId,
inputAccessToken
}
let userData = null;
stackerAmqp.validateUserByFBGraph(message, async (err, data) => {
console.log(`\nFrom "Facebook Auth Services"`);
console.log(`Data: ${JSON.stringify(data, null, 2)}`);
const queueData = JSON.parse(data);
userData = queueData.data;
if(queueData.error === null){
console.log(`\nRegister Services`);
const user = await registerUser.addUser({ userId: userData.id, name: userData.name, email: userData.email });
console.log(`User registered in DB`);
console.log(user);
stackerAmqp.createAccount(userData.name, async (err, data) => {
const stellarAccount = JSON.parse(data);
await registerUser.updateStellarAccount({
userId,
account: stellarAccount.account,
encryptedMnemonic: stellarAccount.mnemonic
});
stackerAmqp.sendFreeToken(
data,
async (err, data1) => {
if (data1 === "Transferred Tokens") {
await registerUser.changeAccountStatus({
userId,
accountStatus: "Completed"
});
//Calling email Services
stackerAmqp.addEmailDataInQueue({ name: userData.name, email: userData.email, userRegistration:true,freeTokens:10 })
res.json({
status: true,
Result: "User registered"
});
}
}
);
});
}
else{
console.log(`Error from Facebook Auth Services`);
console.log(queueData.error);
res.json({
status: false,
message: "Error authenticating user"
});
}
});
}
catch (ex) {
console.log("\nError sending response\n");
console.log(ex);
res.json({
status: false,
message: "Internal Server Error"
});
}
};
<file_sep>const EntitySchema = require("typeorm").EntitySchema; // import {EntitySchema} from "typeorm";
const AccountTypeModel = require("../model/AccountType");
module.exports = new EntitySchema({
name :"AccountType",
target:AccountTypeModel,
columns:{
accountTypeId:{
primary :true,
type:"int",
objectId:true
},
accountTypeName:{
type:"varchar"
}
}
})<file_sep>const { MongoClient } = require("mongodb");
const env = require("../config/env_variables").getEnv();
class StackerMongoConnect {
async connect(connectionString, dbName){
const connection = await MongoClient.connect(connectionString, { useNewUrlParser: true });
const database = connection.db(dbName);
this.collections()
.map(colName => database.collection(colName))
.forEach(col => {
let name = col.collectionName;
let modCollectionName = name.slice(0, 1).toLowerCase() + name.slice(1, name.length);
this[modCollectionName] = col;
});
}
}
module.exports = StackerMongoConnect;
<file_sep>const env = require("../../config/env_variables").getEnv();
const pubsub = require("../../config/pubsub");
exports.FBServices_Authentication =
async (data, correlationId, requestId) => await pubsub(
"FBService_Authentication",
env.rabbitmq.queue.req.authFacebook,
env.rabbitmq.queue.res.authFacebook,
data,
correlationId,
requestId
);
exports.StellarServices_CreateAccount =
async (data, correlationId, requestId) => await pubsub(
"StellarService_CreateAccount",
env.rabbitmq.queue.req.accountCreation,
env.rabbitmq.queue.res.accountCreation,
data,
correlationId,
requestId
);
exports.StellarServices_FreeTokens =
async (data, correlationId, requestId) => await pubsub(
"StellarService_FreeTokens",
env.rabbitmq.queue.req.freeTokens,
env.rabbitmq.queue.res.freeTokens,
data,
correlationId,
requestId
);
<file_sep>### Environment Variables
```
# Database
MongoDB_Url=mongodb://localhost:27017
MongoDB_Name=StackerUsers
# RabbitMQ
AMPQ_Url=amqp://localhost
AMPQ_Queue_Req_AccountCreation=@request/accountCreation
AMPQ_Queue_Res_AccountCreation=@response/accountCreation
AMPQ_Queue_Req_FreeTokens=@request/freeTokens
AMPQ_Queue_Res_FreeTokens=@response/freeTokens
AMPQ_Queue_Req_AuthFacebook=@request/authUser_Facebook
AMPQ_Queue_Res_AuthFacebook=@response/authUser_Facebook
AMPQ_Queue_SendEmail=@sendEmail/registerUser
AMPQ_Queue_Req_Balance=@request/balance
AMPQ_Queue_Res_Balance=@response/balance
# General
Privacy_Version=1.0
Terms_Version=1.0
PORT=7000
```<file_sep>const rabbitMQ = require("../utils/RabbitMQ");
const logger = require("./logger");
const chalk = require("chalk").default;
const log = message => logger.info(chalk.yellow(message));
module.exports = async (requestName, requestQueue, responseQueue, data, correlationId, requestId,exchange) => {
const [consumer, producer] = [rabbitMQ.getConsumer(), rabbitMQ.getProducer()];
const _data = typeof data === "object" ? JSON.stringify(data) : data;
log(`request ${requestId} calls ${requestName}`)
log(`${requestId} RabbitMQ requests ${requestName} with correlationId(${correlationId})`);
log(`${requestId} RabbitMQ requests ${requestName} with exchange(${exchange})`);
producer.assertExchange(exchange,"topic",{durable:true});
producer.assertQueue(requestQueue);
producer.sendToQueue(requestQueue, Buffer.from(_data), { correlationId });
return new Promise((resolve, reject) => {
consumer.assertExchange(exchange,"topic",{durable:true});
consumer.assertQueue(responseQueue);
consumer.consume(responseQueue, (msg) => {
consumer.ack(msg);
consumer.cancel(msg.fields.consumerTag);
log(`${requestId} RabbitMQ received response from ${requestName}`);
log(`${requestId} comparing correlationId from rabbitmq ${msg.properties.correlationId} with requests correlationId ${correlationId}`);
//if(msg.properties.correlationId === correlationId){
const _msg = JSON.parse(msg.content.toString());
console.log(_msg);
if(_msg.data){
console.log("msg.data true >>> ");
resolve([_msg.data,msg.properties.correlationId]);
}
else if(_msg.error){
console.log("msg.error true >>> ");
reject([_msg.error,msg.properties.correlationId]);
}
//}
});
});
};<file_sep>require("dotenv").config({ path: "../.env" });
require("../src/config/env_variables").parse();
const express = require("express");
const app = express();
const env = require("../src/config/env_variables").getEnv();
const registerUser = require("../src/database");
const amqp = require("./rabbit");
const fb = require("./facebook");
const uuid = require("uuid/v4");
require("../src/express-middlewares")(app);
app.post("/user/v1/register", async (req, res) => {
const { accessToken, authProvider, signedRequest } = req.body;
req.uuid = uuid();
const v = uuid();
console.log(`Incoming request: ${req.uuid}`);
fb.request(amqp.producer, { correlationId: req.uuid, accessToken, authProvider, signedRequest });
fb.response(amqp.consumer, v, (msg) => {
console.log(msg.fields);
console.log(req.uuid);
console.log(msg.properties.correlationId);
// if(msg.properties.correlationId === correlationId){
res.json({
data: msg
});
// }
});
});
process.on('uncaughtException', function (err) {
console.log(err.message);
console.log(err.stack);
});
(async () => {
try {
await registerUser.connect(env.mongodb.url, env.mongodb.dbName);
await amqp.config();
app.listen(env.port, () => console.log("Registration Services started at port %s", env.port));
}
catch (ex) {
console.log(`\nError starting the service\n`);
console.log(ex);
process.exit(0);
}
})()
<file_sep>class AccountType {
constructor(id, name) {
this.accountTypeId = id;
this.accountTypeName = name;
}
}
module.exports = AccountType; | 6e60ce796653b9100bcf2b2ef249b540105e9e8a | [
"JavaScript",
"Markdown"
] | 25 | JavaScript | anuragmishra02/nodejs-mongo | 960efb71a6c4bbdb85ac29cf91901a11d88b18e6 | 77ea26c217ac3faa84b572b6baf9c6964acd5842 | |
refs/heads/main | <file_sep>from django.urls import path
from .views import home, post_detail, about
urlpatterns = [
#path(url-name, function)
path('', home),
path('posts/<int:id>', post_detail),
path('about',about),
]
<file_sep>from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=80)
body = models.TextField()
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
feature_pic = models.ImageField(upload_to="cover/", null=True, blank=True)
def __str__(self):
return self.title<file_sep>from django.contrib import admin
from .models import Post
from django_summernote.admin import SummernoteModelAdmin
# Register your models here.
class PostAdmin(SummernoteModelAdmin):
summernote_fields = '__all__'
list_display = [
'title',
'date_created',
'date_updated'
]
admin.site.register(Post, PostAdmin)
<file_sep>from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
# Create your views here.
def home(request):
#Get all posts
all_posts = Post.objects.all()
return render(request, 'blog/home.html', {'posts' : all_posts})
def post_detail(request, id):
# Get only one post
single_post = Post.objects.get(pk=id)
return render(request, 'blog/post-detail.html', {'post': single_post})
def about(request):
return render(request, 'blog/about.html')
| 230082e8e0a4c331f6fe891d0097da7b48ffd2e9 | [
"Python"
] | 4 | Python | varanipit/heroku-rep | 8e55de8485763893b3b5ee90058e4a131aa3ab18 | 98e4e795416dd693313ef6724b0e96f448b7f65a | |
refs/heads/master | <file_sep>module.exports = {
"errno": 0,
"data": {
"pageMark": "total",
"showButton": false,
"request": {
"api": '/api/audit/total/data',
"method": 'get',
"apiParams": ['all']
},
"pageGoBackUrl": '',
"tableList": [
{
"title": '用户上传信息',
"type": 'table',
"sectionKey": 'baseInfo',
"needClearData": true,
"needShowDownLoadButton": false,
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"key": 'value',
"width": 'auto'
}
]
}
},
{
"title": '用户案件描述',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'caseDes',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"key": 'value',
"width": 'auto'
}
]
}
},
{
"title": '用户更多信息',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'moreInfo',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"key": 'value',
"width": 'auto'
}
]
}
},
{
"title": '用户图片信息',
"type": 'table',
"needShowDownLoadButton": true,
"needClearData": true,
"sectionKey": 'uploadMaterial',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '图片列表',
"slot": 'value',
"width": 'auto',
"formFields": [
{
"type": 'List',
"model": 'value',
'cardWidth': '120px',
'cardHeight': '90px'
}
]
}
]
}
},
{
"title": '材料初审建议',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'firstComment',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"key": 'value',
"width": 'auto'
}
]
}
},
{
"title": '材料复审建议',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'secondComment',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"key": 'value',
"width": 'auto'
}
]
}
},
{
"title": '线下调查建议',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'offlineComment',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"width": 'auto',
"key": 'value',
}
]
}
},
{
"title": '线下调查链接',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'offlineCommentLink',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"width": 'auto',
"slot": 'value',
formFields: [
{
type: 'Button',
model: 'value',
textModel: 'value',
subtype: 'text',
action: {
type: 'url',
}
}
]
}
]
}
},
{
"title": '材料终审建议',
"type": 'table',
"needShowDownLoadButton": false,
"needClearData": true,
"sectionKey": 'checkConsolusion',
"showTableHeader": false,
"table": {
"columns": [
{
"title": '项',
"key": 'label',
"width": 150
},
{
"title": '值',
"key": 'value',
"width": 'auto'
}
]
}
}
]
},
"msg": "ok"
}
<file_sep>/**
* @file 路径配置配置
* @author wangbing11(<EMAIL>)
*/
import Main from "../components/layout/default";
const routersContext = require.context("../page/", true, /router\.js$/);
const routers = routersContext.keys().map(key => {
return routersContext(key).default;
});
export default [
{
path: "/",
redirect: "/home",
component: Main,
children: [...[].concat(...routers)]
}
// {
// path: '/401',
// name: 'error_401',
// meta: {
// hideInMenu: true
// },
// component: () => import('@/view/error-strategy/401.vue')
// },
// {
// path: '/500',
// name: 'error_500',
// meta: {
// hideInMenu: true
// },
// component: () => import('@/view/error-page/500.vue')
// },
// {
// path: '*',
// name: 'error_404',
// meta: {
// hideInMenu: true
// },
// component: () => import('@/view/error-page/404.vue')
// }
];
| 0f0bd15f069bc2e1ce2caeca7a1c746e12f360de | [
"JavaScript"
] | 2 | JavaScript | BingBlog/cp-example | 988b023d451becfd34aa0f97785c67a17fad0ab8 | dd9dd9f5a1a914e5673ae2679ef92131ed66d7f1 | |
refs/heads/main | <file_sep>#include "DoubleScriptedArray.h"
#include <iostream>
using namespace std;
int main(){
DoubleScriptedArray array1(4, 5);
cout << array1 << endl;
DoubleScriptedArray array2 (4, 5);
cout << array2 << endl;
cout << (array1 == array2) << endl;
array2(2,3) = 4;
array1 = array2;
cout << array2 << endl;
}<file_sep>#ifndef TWODAYPACKAGE_H
#define TWODAYPACKAGE_H
#include <string>
#include "Package.h"
class TwoDayPackage : public Package{
public:
explicit TwoDayPackage(Customer&, Customer&, double, double, double);
double getFlatFee() const;
double calculateCost() const;
void setFlatFee(double);
private:
double flatFee;
};
#endif<file_sep>#include "TwoDayPackage.h"
TwoDayPackage::TwoDayPackage(Customer& sender, Customer& recipient,
double weight, double costPerOunce, double flatFee)
: Package{sender, recipient, weight, costPerOunce}, flatFee{flatFee}{
/* empty body */
}
double TwoDayPackage::getFlatFee() const{
return flatFee;
}
double TwoDayPackage::calculateCost() const{
return (Package::calculateCost() + flatFee);
}
void TwoDayPackage::setFlatFee(double flatFee){
this->flatFee = flatFee;
}
<file_sep>#ifndef _BANKACCOUNT_H
#define _BANKACCOUNT_H
class BankAccount{
public:
BankAccount(std::string n, double d);
void deposit(double amount);
void withdraw(double amount);
private:
std::string name;
double balance;
};
#endif // BANKACCOUNT_H
<file_sep>/*
* CS 106B/X, <NAME>, <NAME>
* This instructor-provided file contains the implementation of the Board class,
* used in the 8 Queens example. We didn't write this code in class.
* See Board.h for documentation of each member.
*/
#include "Board.h"
#include "gui.h"
#include "grid.h"
using namespace std;
Board::Board(int size) : _nplaced(0)
{
if (size < 1) {
throw size;
}
_board.resize(size, size);
GUI::initialize(size);
}
bool Board::isOccupied(int row, int col) const
{
return _board.inBounds(row, col) && _board[row][col];
}
bool Board::isSafe(int row, int col) const
{
GUI::consider(row, col);
for (int i = 0; i < _board.numRows(); i++) {
if (isOccupied(i, col) || // other rows in this colum
isOccupied(row, i) || // other cols in this row
isOccupied(row + i, col + i) || // SE diag
isOccupied(row - i, col - i) || // NW diag
isOccupied(row - i, col + i) || // NE diag
isOccupied(row + i, col - i)) // SW diag
{
if (col == _board.numCols() - 1) {
GUI::backtrack(row, col);
}
return false;
}
}
return true;
}
void Board::place(int row, int col)
{
_board[row][col] = true;
GUI::occupy(row, col);
if (++_nplaced == _board.numRows()) {
GUI::showSolution(_board);
}
}
void Board::remove(int row, int col)
{
_board[row][col] = false;
GUI::leave(row, col);
_nplaced--;
if (col == _board.numCols() - 1) {
GUI::backtrack(row, col);
}
}
int Board::size() const
{
return _board.numRows();
}
<file_sep>#include "Soldier.h"
using namespace std;
Soldier::Soldier(std::string name, std::string startDate)
:name{name}{
setStartDate(startDate);
setEndDate();
}
string Soldier::getStartDate() const{
return startDate;
}
string Soldier::getEndDate() const{
return endDate;
}
void Soldier::setStartDate(string startDate){
}
void Soldier::setEndDate(){
}
string Soldier::calculateEndDate(){
string endDate;
return endDate;
}<file_sep>/*
* CS 106B/X, <NAME>
* This instructor-provided file contains the declaration of the Board class,
* used in the 8 Queens example. We didn't write this code in class.
*/
#ifndef _board_h
#define _board_h
#include <iostream>
#include <string>
#include "grid.h"
using namespace std;
class Board {
public:
/*
* Constructs a board of the given size (rows x columns).
* Throws an integer exception if the size is less than 1.
*/
Board(int size);
/*
* Returns true if it is safe to place a queen at the given row/column
* position, meaning that no other existing queen can capture it.
* Throws a string exception if the row or column is out of bounds of the board.
*/
bool isSafe(int row, int col) const;
/*
* Places a queen at the given row/col position.
* Does not check whether it is safe to do so; call isSafe or isValid for that.
* Throws a string exception if the row or column is out of bounds of the board.
*/
void place(int row, int col);
/*
* Un-places a queen from the given row/col position.
* If there wasn't a queen there, has no effect.
* Throws a string exception if the row or column is out of bounds of the board.
*/
void remove(int row, int col);
/*
* Returns the board's size, its number of rows and columns.
* A default chess board would have 8 rows and columns.
*/
int size() const;
/*
* Show the solution on current board.
*/
void showSolution() const;
private:
Grid<bool> _board; // grid of board squares (true=queen, false=empty)
int _nplaced;
bool isOccupied(int row, int col) const;
};
#endif
<file_sep>#include "arraystack.h"
#include "strlib.h"
ArrayStack::ArrayStack(){
}
ArrayStack::~ArrayStack(){
//destructor: clean up the memory
delete[] elements;
}
void ArrayStack::push(int n){
}
int ArrayStack::peek() const{
return 0;
}
bool ArrayStack::isEmpty() const{
return true;
}
std::string ArrayStack::toString() const{
std::string s = "{";
for(int i=0;i<size;i++){
s += " " + integerToString(elements[i]);
}
return s + "}";
}
ostream& operator <<(ostream& out, ArrayStack& stack){
out << stack.toString();
return out;
}
<file_sep>#include "Polynomial.h"
Polynomial::Polynomial(){
}
Polynomial::Polynomial(int deg){
this->degree = deg;
}
Polynomial::~Polynomial(){
delete degree;
delete[] ptr;
}
Polynomial::Polynomial(const Polynomial& p){
this->degree = p.degree;
// declare new ptr array then copy values.
this->ptr = new double[p.degree];
for(int i=0;i<this->degree;i++){
ptr[i] = p.ptr[i];
}
}
Polynomial Polynomial::operator+(const Polynomial& p){
Polynomial result;
if(p.degree <= this->degree){
// if degree of polynomial parameter is smaller/equal
result.degree = this->degree;
for(int i=0;i<this->degree;i++){
if(i <= p.degree){
result.ptr[i] = this->ptr[i] + p.ptr[i];
} else{
result.ptr[i] = this->ptr[i];
}
}
} else{
// if degree of polynomial parameter is larger
result.degree = p.degree;
for(int i=0;i<p.degree;i++){
if(i <= this->degree){
result.ptr[i] = this->ptr[i] + p.ptr[i];
} else{
result.ptr[i] = p.ptr[i];
}
}
}
return result;
}
const Polynomial& Polynomial::operator=(const Polynomial){
}<file_sep>// This is the CPP file you will edit and turn in.
// Also remove these comments here and add your own.
// TODO: remove this comment header!
#include <cctype>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include "console.h"
#include "filelib.h"
#include "grid.h"
#include "gwindow.h"
#include "simpio.h"
#include "lifegui.h"
using namespace std;
void nextGrid(Grid<string>& grid, string wrapAround);
void printGrid(Grid<string>& grid);
void getNeighborGrid(Grid<string>& gridInput, Grid<string>& gridNeighbor, string wrapAround);
void updateGUI(Grid<string>& grid, LifeGUI& gui);
string calculateNeighborUnwrapped(Grid<string>& grid, int row, int col);
string calculateNeighborWrapped(Grid<string>& grid, int row, int col);
int main() {
// Prompt user for a file name
ifstream stream;
promptUserForFile(stream, "Grid input file name? ");
// Get parameters for grid
string rowString, colString;
getline(stream, rowString);
getline(stream, colString);
Grid<string> grid(stringToInteger(rowString), stringToInteger(colString));
string tempRows;
for(int i=0;i<grid.numRows();i++){
getline(stream, tempRows);
for(int j=0;j<grid.numCols();j++){
grid[i][j] = tempRows[j];
}
}
stream.close();
printGrid(grid);
// Ask if simulation should wrap around the grid
string wrapAround;
while(true){
cout << "Should the simulation wrap around the grid (y/n)?";
cin >> wrapAround;
if(wrapAround == "y" || wrapAround == "n"){
break;
}
}
//printGrid(gridNeighbor);
// Add GUI
LifeGUI name;
name.resize(grid.numRows(), grid.numCols());
// Now simulate the animate/tick/quit part
string nextStep;
do{
while(true){
cout << "a)nimate, t)ick, q)uit? ";
cin >> nextStep;
nextStep = toLowerCase(nextStep);
if(nextStep == "a" || nextStep == "t" || nextStep == "q"){
break;
}
}
if(nextStep == "a"){
// implement here!
string framesString;
int frames;
while(true){
cout << "How many frames? ";
cin >> framesString;
if(stringIsInteger(framesString)){
frames = stringToInteger(framesString);
break;
} else{
cout << "Illegal integer format. Try again." << endl;
}
}
// now animate!
for(int i=0;i<frames;i++){
clearConsole();
nextGrid(grid, wrapAround);
printGrid(grid);
updateGUI(grid, name);
pause(50);
}
}
if(nextStep == "t"){
// implement here!
nextGrid(grid, wrapAround);
printGrid(grid);
updateGUI(grid, name);
}
} while(nextStep != "q");
cout << "Have a nice Life!" << endl;
return 0;
}
void updateGUI(Grid<string>& grid, LifeGUI& gui){
for(int i=0;i<grid.numRows();i++){
for(int j=0;j<grid.numCols();j++){
bool alive = (grid[i][j] == "X");
gui.drawCell(i, j, alive);
}
}
}
void nextGrid(Grid<string>& grid, string wrapAround){
// Calcuate grid that contains neighbor for each cell.
Grid<string> gridNeighbor(grid.numRows(), grid.numCols());
getNeighborGrid(grid, gridNeighbor, wrapAround);
// Update current grid by the rules.
for(int i=0;i<gridNeighbor.numRows();i++){
for(int j=0;j<gridNeighbor.numCols();j++){
// Many cases of neighbors
int neighbor = stringToInteger(gridNeighbor[i][j]);
if(neighbor == 0 || neighbor == 1){
grid[i][j] = "-";
} else if(neighbor == 2){
continue;
} else if(neighbor == 3){
grid[i][j] = "X";
} else{
grid[i][j] = "-";
}
}
}
}
// Obtain the grid of strings that contain the neighbors to each cell.
void getNeighborGrid(Grid<string>& grid, Grid<string>& gridNeighbor, string wrapAround){
if(wrapAround == "y"){
for(int i=0;i<grid.numRows();i++){
for(int j=0;j<grid.numCols();j++){
gridNeighbor[i][j] = calculateNeighborWrapped(grid, i, j);
}
}
}
else if(wrapAround == "n"){
for(int i=0;i<grid.numRows();i++){
for(int j=0;j<grid.numCols();j++){
gridNeighbor[i][j] = calculateNeighborUnwrapped(grid, i, j);
}
}
}
else{
cout << "ERROR in wrapAround parameter" << endl;
}
}
string calculateNeighborUnwrapped(Grid<string>& grid, int row, int col){
// Initialize sum
int sum = 0;
// Go through the neighbors
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(i==1 && j==1){
// do not include itself
continue;
}
else if ((row+i-1)>=0 && (row+i-1)<grid.numRows() &&
(col+j-1)>=0 && (col+j-1)<grid.numCols()){
// use grid.inBounds()!!
// add if only within bounds
sum += ((grid[row+i-1][col+j-1] == "X")? 1:0);
}
else{
// other non-relevant cases
continue;
}
}
}
return integerToString(sum);
}
string calculateNeighborWrapped(Grid<string>& grid, int row, int col){
//Initialize sum
int sum = 0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
if(i==1 && j==1){
// do not include itself
continue;
} else{
// wrap around edges and add.
sum += ((grid[(row+(i-1)+grid.numRows())%grid.numRows()][(col+(j-1)+grid.numCols())%grid.numCols()] == "X")? 1:0);
}
}
}
return integerToString(sum);
}
void printGrid(Grid<string>& grid){
for(int i=0;i<grid.numRows();i++){
for(int j=0;j<grid.numCols();j++){
cout << grid[i][j];
}
cout << endl;
}
}
<file_sep>/*
* File: grammarsolver.cpp
* --------------------------
* Name:
* Section leader:
* This file contains grammar generating code for CS106B.
*/
#include "grammarsolver.h"
#include "stdio.h"
#include "strlib.h"
#include "map.h"
#include "set.h"
#include "vector.h"
#include "random.h"
#include <iostream>
#include <fstream>
using namespace std;
// Rewrite after figuring this mess out.
/*
void grammarHelper(string& result, string symbol, Set<string>& leftSymbol,
Map<string, Vector<string>>& grammar){
cout << "Symbol: " << symbol << endl;
// determine if the rules to this symbol, modify symbol if it does not conform to rules
bool isNonter = leftSymbol.contains(symbol);
if(leftSymbol.contains(symbol)){
// do nothing;
} else{
bool isWithin;
Vector<string> splitSymbol = stringSplit(symbol, "|");
for(int i=0;i<splitSymbol.size();i++){
if(leftSymbol.contains(symbol)){
isWithin = true;
}
}
if(isWithin){
int randomChoice = randomInteger(0, splitSymbol.size()-1);
symbol = splitSymbol[randomChoice];
}
}
cout << "Symbol after mod: " << symbol << endl;
if(leftSymbol.contains(symbol)){
Vector<string> rule = grammar.get(symbol);
cout << "rules: " << rule << endl;
if(rule.size() == 1){
Vector<string> choices = stringSplit(rule[0], "|");
cout << "choices: " << choices << endl;
int randomChoice =randomInteger(0, choices.size()-1);
cout << choices[randomChoice] << endl;
cout << "result: " << result << endl;
result = result + " " + choices[randomChoice];
grammarHelper(result, choices[randomChoice], leftSymbol, grammar);
} else{
for(int i=0;i<rule.size();i++){
int randomChoice = randomInteger(0, rule.size()-1);
cout << rule[randomChoice] << endl;
cout << "result: " << result << endl;
grammarHelper(result, rule[randomChoice], leftSymbol, grammar);
}
}
} else{
}
}
*/
/**
* Generates grammar for a given symbol a certain number of times given
* a BNF input file.
*
* This will be called by grammarmain.cpp.
*
* @param input - Input stream of BNF file.
* @param symbol - Symbol to generate
* @param times - Number of times grammar is generated
* @return Vector of strings of size times with random generations of symbol
*/
Vector<string> grammarGenerate(ifstream& input, string symbol, int times) {
// Part 1: Read all of the inputs
Vector<string> expansion;
Map<string, Vector<string>> grammar;
Set<string> leftSymbol;
string line;
while(getline(input, line)){
Vector<string> lineSplit;
Vector<string> ruleSplit;
lineSplit = stringSplit(line, "::=");
ruleSplit = stringSplit(lineSplit[1], " ");
cout << ruleSplit << endl;
if(leftSymbol.contains(lineSplit[0])){
throw("two lines for same non-terminal");
}
leftSymbol.add(lineSplit[0]);
grammar.add(lineSplit[0], ruleSplit);
}
//cout << grammar << endl;
//cout << leftSymbol << endl;
for(int i=0;i<times;i++){
string result = "";
grammarHelper(result, symbol, leftSymbol, grammar);
cout << "result: " << result << endl;
expansion.add(result);
}
return expansion; // This is only here so it will compile
}
<file_sep>#include "std_lib_facilities.h"
/* First attempt at writing a calculator with + and -
*/
int main()
{
cout << "Please enter an expression containing either + or -: ";
int lval;
int rval;
char op;
int res;
cin >> lval >> op >> rval;
if(op == '+'){
res = lval + rval;
} else if(op == '-'){
res = lval - rval;
}
cout << "Result : " << res << endl;
return 0;
}<file_sep>// This is the CPP file you will edit and turn in.
// Also remove these comments here and add your own.
// TODO: remove this comment header
#include <cctype>
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include "console.h"
#include "filelib.h"
#include "simpio.h"
#include "random.h"#include "set.h"
#include "map.h"
#include "queue.h"
using namespace std;
int main() {
// Introduction
cout << "Welcome to CS 106B Random Writer (\'N-Grams\')." << endl;
cout << "This program makes random text based on a document." << endl;
cout << "Give me an input file and an 'N' value for groups" << endl;
cout << "of words, and I'll create random text for you." << endl;
// Get files and N
ifstream stream;
promptUserForFile(stream, "Input File Name? ");
int n = getInteger("Value of N? ");
// get your maps!
Vector<string> words;
Map<Vector<string>, Vector<string>> m;
string word;
while (stream >> word) {
// each time through this loop, word is the next word in the file
words.add(word);
}
Vector<string> key;
string nextWord;
for(int i=0;i<n-1;i++){
key.add(words[i%words.size()]);
}
//cout << words;
Vector<string> tempVector;
tempVector.add(words[(n-1)%(words.size())]);
m[key] = tempVector;
for(int i=n-1;i<words.size();i++){
// update keys
key.add(words[i%words.size()]);
key.remove(0);
// retrieve next word
nextWord = words[(i+1)%words.size()];
// update map
if(m.containsKey(key)){
m[key].add(nextWord);
}
else{
Vector<string> tempVector;
tempVector.add(nextWord);
m[key] = tempVector;
}
}
//cout << m << endl;
int numWords;
Vector<string> ngrams;
do{
numWords = getInteger("# of random words to generate (0 to quit)? ");
int start = randomInteger(0, (m.keys().size()-1));
key = m.keys().get(start);
cout << key << endl;
ngrams.addAll(key);
string val = (m[key]).get(randomInteger(0, (m[key].size()-1)));
ngrams.add(val);
int count = n;
while(count <= numWords){
// update key
key.add(val);
key.remove(0);
val = m[key].get(randomInteger(0, (m[key].size()-1)));
cout << val << endl;
ngrams.add(val);
count += 1;
}
cout << "...";
for(int i=0;i<numWords;i++){
cout << ngrams[i] << " ";
}
cout << "..." << endl;
} while((numWords != 0));
cout << "Exiting." << endl;
return 0;
}
<file_sep>#include "ArrayStack.h"
#include "error.h"
ArrayStack::ArrayStack(){
elements = new int[10]();
size = 0;
capacity = 10;
}
void ArrayStack::push(int n){
if(size < capacity){
elements[size] = n;
size++;
} else{
//TODO: out of space?
}
}
int ArrayStack::peek(){
if(size == 0){
} else{
return (elements[size-1]);
}
}
int ArrayStack::pop(){
if(size == 0){
//error?
} else{
int result = elements[size-1];
size--;
return result;
}
}
bool ArrayStack::isEmpty(){
return (size == 0);
}
std::string toString(){
std::string s "";
for(int i=0;i<size;i++){
s += " " + integerToString(elements[i]);
}
return s;
}
<file_sep>/*
* CS 106B/X, <NAME>
*
* This code contains code to solve the "8 Queens" problem on a chess board
* using recursive backtracking.
*/
#include <iostream>
#include "Board.h"
#include "console.h"
using namespace std;
// function prototype declarations
void solveQueens(Board& board);
/*
* Searches the given chess board for a solution to the N Queens problem
* of trying to place N queen pieces on a chess board without any of them
* being able to capture each other.
*/
int main()
{
Board board(8);
solveQueens(board);
return 0;
}
/*
* Function: solveQueens
* ---------------------
* This function is the main entry in solving the N queens problem.
* It takes the partially-filled board and the row index we are trying
* to place a queen in. It will return a boolean value which indicates
* whether or not we found a successful arrangement starting
* from this configuration.
*
* Base case: if there are no more queens to place,
* then we have successfully solved the problem!
*
* Otherwise, we find a safe column in this row, place a queen at
* (row,col) of the board and recursively call solveQueens starting
* at the next row using this new board configuration.
* If that solveQueens call fails, we will remove that queen from (row,col)
* and try again with the next safe column within the row.
* If we have tried all the columns in this row and did not
* find a solution, then we return false, which then backtracks
* out of this unsolvable partial configuration.
*
* The initial call to solveQueens should an empty board and
* placing a queen in row 0.
*/
void solveQueens(Board& board){
solveQueens(board, 0);
}
void solveQueensHelper(Board& board, int col){
if(col == board.size()){
cout << board << endl;
} else{
// choose (for each row)
for(int row=0;row<board.size();row++){
//choose
if(board.isSafe(row, col)){
board.place(row, col);
//explore
solveQueensHelper(board, col+1);
//unchoose
board.remove(row, col);
}
}
}
}
<file_sep>#ifndef LINKEDINTLIST_H
#define LINKEDINTLIST_H
#include "ListNode.h"
#include <iostream>
using namespace std;
class LinkedIntList
{
public:
LinkedIntList();
~LinkedIntList();
private:
LIstNode* front;
};
#endif // LINKEDINTLIST_H
<file_sep>// This is the CPP file you will edit and turn in.
// Also remove these comments here and add your own, along with
// comments on every function and on complex code sections.
// TODO: remove this comment header
#include "encoding.h"
#include <iostream>
#include "pqueue.h"
#include "filelib.h"
using namespace std;
// TODO: include any other headers you need
Map<int, int> buildFrequencyTable(istream& input) {
// TODO: implement this function
Map<int, int> freqTable;
int c;
while((c = input.get()) != EOF){
freqTable[c]++;
}
// add this for EOF (once per file)
freqTable[PSEUDO_EOF]++;
return freqTable;
}
HuffmanNode* buildEncodingTree(const Map<int, int>& freqTable) {
// Priority queue to store our node structs
PriorityQueue<HuffmanNode*> pq;
// Construct pq by traversing our freqTable
for(int c: freqTable.keys()){
HuffmanNode *tempNode = new HuffmanNode(c, freqTable[c], NULL, NULL);
pq.enqueue(tempNode, freqTable[c]);
}
/*
for(HuffmanNode* t : pq){
cout << t->character << " " << t->count << endl;
}
*/
while(pq.size() >= 2){
// Remove two nodes from the beginning of the pq
HuffmanNode* node1 = pq.dequeue();
HuffmanNode* node2 = pq.dequeue();
// Join two nodes
HuffmanNode* node3 = new HuffmanNode();
node3->count = node1->count + node2->count;
// Place original nodes as children of new node
node3->zero = node1;
node3->one = node2;
// Re-insert into pq
pq.enqueue(node3, node3->count);
}
// return the only node (which is in the front)
return pq.front();
}
void buildEncodingMapHelper(Map<int, string>& encodingMap, HuffmanNode* node, string& binary){
// base case
if(node->isLeaf()){
encodingMap.add(node->character, binary);
} else{
// left traversal
binary += "0"; // choose
buildEncodingMapHelper(encodingMap, node->zero, binary);
binary = binary.substr(0, binary.length()-1); // unchoose
// right traversal
binary += "1"; // choose
buildEncodingMapHelper(encodingMap, node->one, binary);
binary = binary.substr(0, binary.length()-1); // unchoose
}
}
Map<int, string> buildEncodingMap(HuffmanNode* encodingTree) {
Map<int, string> encodingMap;
string binary = "";
// call to recursive helper function
buildEncodingMapHelper(encodingMap, encodingTree, binary);
return encodingMap;
}
void encodeData(istream& input, const Map<int, string>& encodingMap, obitstream& output) {
// Read file character by character
int c;
string encode = "";
while((c = input.get()) != EOF){
encode = encodingMap[c];
for(int i=0;i<encode.length();i++){
output.writeBit(stringToInteger(encode.substr(i, 1)));
}
}
// add code for EOF
encode = encodingMap[PSEUDO_EOF];
for(int i=0;i<encode.length();i++){
output.writeBit(stringToInteger(encode.substr(i, 1)));
}
}
void decodeData(ibitstream& input, HuffmanNode* encodingTree, ostream& output) {
// Read file character by character
int c;
HuffmanNode* temp;
temp = encodingTree;
//string tempString = "";
while(true){
if(temp->isLeaf()){
// leaf: we found the character.
// Add if character is not the EOF character.
if(temp->character != PSEUDO_EOF){
output << char(temp->character);
temp = encodingTree;
//cout << tempString << endl;
//StempString = "";
} else{
break;
}
} else{
// Read in next chacter
c = input.readBit();
// not a leaf: we need to traverse further.
if(c == 1){
temp = temp->one;
//StempString += "1";
} else if (c == 0){
temp = temp->zero;
//tempString += "0";
} else if (c == -1){
break;
} else{
throw "Invalid File";
}
}
}
}
void compress(istream& input, obitstream& output) {
// Build Frequency Table
Map<int, int> freqTable = buildFrequencyTable(input);
rewindStream(input);
// Build encoding tree
HuffmanNode* front = buildEncodingTree(freqTable);
// Build encoding map
Map<int, string> encodingMap = buildEncodingMap(front);
// write encodingMap into output file as a header
output << freqTable;
// encode data
encodeData(input, encodingMap, output);
}
void decompress(ibitstream& input, ostream& output) {
Map<int, int> freqTable;
input >> freqTable;
HuffmanNode* encodingTree = buildEncodingTree(freqTable);
decodeData(input, encodingTree, output);
}
void freeTreeHelper(HuffmanNode* node){
if(node->isLeaf()){
delete node;
} else{
HuffmanNode* temp = node;
delete node;
freeTreeHelper(temp->one);
freeTreeHelper(temp->zero);
}
}
void freeTree(HuffmanNode* node) {
freeTreeHelper(node);
}
<file_sep>#include <string>
class Date{
static void calculateDifference();
static bool isValidDate(std::string);
public:
Date(std::string);
Date(int, int, int);
std::string toString() const;
private:
int year;
int month;
int day;
};<file_sep>#ifndef DOUBLESCRIPTEDARRAY_H
#define DOUBLESCRIPTEDARRAY_H
#include <iostream>
class DoubleScriptedArray{
// stream extraction/insertion operators
friend std::ostream& operator<<(std::ostream&, const DoubleScriptedArray&);
friend std::istream& operator>>(std::istream&, DoubleScriptedArray&);
public:
explicit DoubleScriptedArray(int = 10, int = 10); // explicit constructor
DoubleScriptedArray(const DoubleScriptedArray&); // copy constructor
~DoubleScriptedArray();
int getRowSize() const;
int getColSize() const;
// overload operators
const DoubleScriptedArray& operator=(const DoubleScriptedArray&); // = operator
bool operator==(const DoubleScriptedArray&) const; // == operator
bool operator!=(const DoubleScriptedArray& right) const {
return !(*this == right);
} // != operator
// subscripting operators
int operator()(int, int) const;
int& operator()(int, int);
private:
// member variables
int row, col;
int* ptr;
};
#endif<file_sep>#include "Date.h"
using namespace std;
bool Date::isValidDate(std::string date){
return true;
}
Date::Date(string date){
}
Date::Date(int year, int month, int day){
this->year = year;
this->month = month;
this->day = day;
}
string Date::toString() const{
}<file_sep>#ifndef PACKAGE_H
#define PACKAGE_H
#include <string>
#include "Customer.h"
class Package{
public:
explicit Package(Customer&, Customer&, double, double);
explicit Package(std::string, std::string, std::string, std::string,
std::string, std::string, std::string, std::string,
double, double);
double getWeight() const;
double getCostPerOunce() const;
double calculateCost() const;
void setWeight(double);
void setCostPerOunce(double);
private:
Customer sender;
Customer recipient;
double weight; // in counces
double costPerOunce; // in cost per ounce
};
#endif<file_sep>#include "linkedintlist.h"
LinkedIntList::LinkedIntList()
{
front = nullptr;
}
LinkedIntList::~LinkedIntList()
{
// loop across the list to delete all nodes.
}
<file_sep>// heappatientqueue.h
// This is the H file you will edit and turn in. (TODO: Remove this comment!)
#pragma once
#include <iostream>
#include <string>
#include "patientnode.h"
#include "patientqueue.h"
using namespace std;
class HeapPatientQueue : public PatientQueue {
public:
struct Patient{
public:
string name;
int priority;
Patient(){}
Patient(string name, int priority){
this->name = name;
this->priority = priority;
}
};
HeapPatientQueue();
~HeapPatientQueue();
string frontName();
void clear();
int frontPriority();
bool isEmpty();
void newPatient(string name, int priority);
string processPatient();
void upgradePatient(string name, int newPriority);
string toString();
private:
int capacity = 10;
int size;
Patient *pq;
void resize();
int comparePatient(Patient p1, Patient p2);
};
<file_sep>#include <iostream>
#include <string>
#include "console.h"
#include "set.h"
#include "vector.h" // for Vector
using namespace std;
void permuteVector(Vector<string> &v);
void permuteVectorHelper(Vector<string> &v, Vector<string> &chosen, Set<Vector<string> > &printed);
int main() {
cout << "Testing the permute function: " << endl;
Vector<string> v;
v.add("A");
v.add("B");
v.add("C");
permuteVector(v);
return 0;
}
void permuteVector(Vector<string>& v){
Vector<string> chosen;
Set<Vector<string>> printed;
permuteVectorHelper(v, chosen, printed);
}
void permuteVectorHelper(Vector<string>& v, Vector<string>& chosen,
Set<Vector<string>>& printed){
// base case
cout << "permute v = " << v << ", chosen= " << chosen << endl;
cout << endl;
if(v.isEmpty()){
if(!printed.contains(chosen)){
cout << chosen << endl;
printed.add(chosen);
}
} else{
for(int i=0;i<v.size();i++){
// choose
string s = v.get(i);
chosen.add(s);
v.remove(i);
// explore
permuteVectorHelper(v, chosen, printed);
// unchoose
int x = chosen.size();
chosen.remove(x-1);
v.insert(i, s);
}
}
}
<file_sep>#include <iostream>
#include "console.h"
#include "gwindow.h" // for GWindow
#include "simpio.h" // for getLine
#include "vector.h" // for Vector
using namespace std;
void sublists(Vector<string>& v);
void sublistsHelper(Vector<string>& current, Vector<string>& remaining);
int main() {
Vector<string> v;
v.add("Jane");
v.add("Bob");
v.add("Matt");
v.add("Sara");
sublists(v);
return 0;
}
void sublists(Vector<string>& v){
Vector<string> s;
sublistsHelper(s, v);
}
void sublistsHelper(Vector<string>& current, Vector<string>& remaining){
// Base case
if(remaining.size() == 0){
cout << current << endl;
} else{
string temp = remaining[0];
remaining.remove(0);
// do not include temp
sublistsHelper(current, remaining);
// include temp in current.
current.insert(0, temp);
sublistsHelper(current, remaining);
// "unchoose"
remaining.insert(0, temp);
current.remove(0);
}
}
<file_sep>#include <iostream>
#include "console.h"
using namespace std;
struct ListNode{
int data;
ListNode* next;
};
/* Incorrect way: duplicate of pointer created.
void addFront(ListNode* front, int value){
ListNode* temp = new ListNode(value);
temp->text = front;
front = temp;
}
*/
void addFront(ListNode*& list, int value){
// instantiating a new struct.
ListNode* temp = new ListNode();
// set value for the node.
temp->data = value;
// the temp node will point to the first node of the previous list.
temp->next = list;
// we are modifying the pointer to point at the first node(temp).
list = temp;
}
void addBack(ListNode*& front, int value){
ListNode* current = front;
// check for null pointer
if(front == nullptr){
front = new ListNode();
front->data = value;
} else{
// this for loop points at the last node of the list
for(;current->next != nullptr;current = current->next);
// insantiate new node that will be the last node.
ListNode* temp = new ListNode();
temp->data = value;
temp->next = nullptr;
// set the last node to be the temp ListNode;
current->next = temp;
}
/* The previous expression is equivalent to
while (list->next != nullptr){
list = list->next;
}
*/
}
void removeFront(ListNode*& front){
if(front != nullptr){
ListNode* temp = front;
front = front->next; // memory leak!!
delete temp; // frees up memory
}
}
void printList(ListNode* front){
while(front != nullptr){
cout << front->data << endl;
front = front->next;
}
}
int main() {
ListNode* front = nullptr;
//addFront(front, 9);
//addFront(front, 17);
//addFront(front, -3);
//addFront(front, 42);
addBack(front, 20);
printList(front);
return 0;
}
<file_sep>
#include "Maze.h"
bool escapeMaze(Maze& maze, int row, int col){
// base case
if(!maze.inBounds(row, col)){
return true;
} else if(maze.isWall(row, col)){
return false;
} else if(!maze.isOpen(row, col)){
// choose step
maze.mark(row, col);
// exploring steps
bool result = escapeMaze(maze, row-1, col) || escapeMaze(maze, row+1, col) ||
escapeMaze(maze, row, col-1) || escapeMaze(maze, row, col+1);
// un-choose if it is not a good result
if(!result){
maze.taint(row, col);
}
return result;
} else{
return false;
}
}
<file_sep>
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <string>
class Customer{
public:
Customer(std::string, std::string, std::string, std::string);
std::string getName() const;
std::string getAddress() const;
std::string getCity() const;
std::string getZipcode() const;
void setName();
void setAddress();
void setCity();
void setZipcode();
private:
std::string name;
std::string address;
std::string city;
std::string zipcode;
};
#endif<file_sep>#include <iostream>
#include "console.h"
#include "gwindow.h" // for GWindow
#include "simpio.h" // for getLine
#include "vector.h" // for Vector
using namespace std;
void printAllBinaryVer01(int digit);
void printAllBinaryVer02(int digit);
void binaryDigitHelper(int digit, string output);
void printDecimal(int digit);
void printDecimalHelper(int digit, string output);
int main() {
int digit;
cout << "Enter number of digits: ";
cin >> digit;
//printAllBinaryVer02(digit);
return 0;
}
void printDecimal(int digit){
printDecimalHelper(digit, "");
}
void printDecimalHelper(int digit, string output){
if(digit == 0){
cout << output << endl;
} else{
for(int i=0;i<9;i++){
printDecimalHelper(digit-1, output + integerToString(i));
}
}
}
void printAllBinaryVer01(int digit){
// base case
if(digit == 1){
cout << 0 << endl;
cout << 1 << endl;
}
// non-base cases
else{
cout << 0;
printAllBinaryVer01(digit-1);
cout << 1;
printAllBinaryVer02(digit-1);
}
}
void printAllBinaryVer02(int digit){
binaryDigitHelper(digit, "");
}
// helper function
void binaryDigitHelper(int digit, string output){
if(digit == 0){
cout << output << endl;
} else{
binaryDigitHelper(digit-1, output + "0");
binaryDigitHelper(digit-1, output + "1");
}
}
<file_sep>#include "Customer.h"
#include <string>
using namespace std;
Customer::Customer(string name, string address, string city, string zipcode)
: name{name}, address{address}, city{city}, zipcode{zipcode}{
/* empty body */
}
string Customer::getName() const{
return name;
}
string Customer::getAddress() const{
return address;
}
string Customer::getCity() const{
return city;
}
string Customer::getZipcode() const{
return zipcode;
}
void Customer::setName(string name){
this->name = name;
}
void Customer::setAddress(string address){
this->address = address;
}
void Customer::setCity(string city){
this->city = city;
}
void Customer::setZipcode(string zipcode){
this->zipcode = zipcode;
}<file_sep>#include "Complex.h"
Complex::Complex(double real, double imag)
: real{real}, imag{imag}{
/* empty body */
}
Complex::Complex(const Complex& c){
real = c.real;
imag = c.imag;
}
Complex Complex::operator+(const Complex& right) const{
return Complex{real + right.real, imag + right.imag};
}
<file_sep>#include <iostream>
using namespace std;
struct TreeNode{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int data){
this->data = data;
}
TreeNode(int data, TreeNode* left, TreeNode* right){
this->data = data;
this->left = left;
this->right = right;
}
bool isLeaf(){
return (left == nullptr) && (right == nullptr);
}
};
void printTree(TreeNode* node){
if(node->right == nullptr && node->left == nullptr){
cout << node->data << endl;
} else{
printTree(node->right);
printTree(node->left);
}
/*
if(node != nullptr){
cout << node->data << endl;
printTree(node->right);
printTree(node->left);
}
*/
}
int sizeTree(TreeNode* node){
if(node == nullptr){
return 0;
}
return 1 + sizeTree(node->right) + sizeTree(node->left);
}
bool contains(TreeNode *node, int value){
if(node == nullptr){
return false;
} else if(node->data == value){
return true;
} else{
return contains(node->right, value) || contains(node->right, value);
}
}
int getMin(TreeNode* node){
if(node->left == nullptr){
return node->data;
} else{
return getMin(node->left);
}
}
int getMax(TreeNode* node){
if(node->right == nullptr){
return node->data;
} else{
return getMax(node->right);
}
}
void remove(TreeNode* &node, int value){
// Need to find the node with the value
if(node->value < value){
remove(node->right, value);
} else if(node->value > value){
remove(node->left, value);
} else{
// found the node: consider four cases.
// 1. leaf
if(node->isLeaf()){
delete node; // delete frees up memory that the poitner points to
node = nullptr; // now make the node point nowhere.
} else if (node->right == nullptr){
// 2. only left subtree
TreeNode *temp = node;
node = node->left;
delete temp;
} else if (node->left == nullptr){
// 3. only right subtree
TreeNode *temp = node;
node = node->right;
delete temp;
} else{
// 4. full tree
// substitute node with the smallest value of the right subtree
int minValue = getMin(node->right);
node->data = minValue;
delete(node->right, minValue);
}
}
}
<file_sep>#ifndef POLYNOMIAL_H
#define POLYNOMIAL_H
class Polynomial{
public:
Polynomial(); // default constructor
Polynomial(int deg);
~Polynomial(); // destructor
Polynomial(const Polynomial& p); // copy constructor
Polynomial operator+(const Polynomial& p);
Polynomial operator-(const Polynomial& p);
const Polynomial& operator=(const Polynomial& p);
Polynomial operator*(const Polynomial& p);
Polynomial operator+=(const Polynomial& p);
Polynomial operator-=(const Polynomial& p);
Polynomial operator*=(const Polynomial& p);
private:
int degree;
double *ptr; // pointer to coefficient array
}
<file_sep>#ifndef COMPLEX_H
#define COMPLEX_H
#include <string>
class Complex{
public:
// constructor, copy constructor, destructor
explicit Complex(double = 0.0, double = 0.0);
Complex(const Complex&);
// operator overloading
Complex operator+(const Complex&) const;
Complex operator-(const Complex&) const;
bool operator==(const Complex&) const;
bool operator!=(const Complex& right) const{
return !((*this) == right);
}
Complex& conjugate(const Complex&);
std::string toString() const;
private:
double real;
double imag;
};
#endif<file_sep>#include <iostream>
#include "console.h"
#include "gwindow.h" // for GWindow
#include "simpio.h" // for getLine
#include "vector.h" // for Vector
using namespace std;
void diceSum(int num, int target);
void diceSumHelper(int num, int target, Vector<int> &values);
int main() {
int num;
num = getInteger("Enter number of dies: ");
int target;
target = getInteger("Enter deisred sum of dies: ");
diceSum(num, target);
return 0;
}
void diceSum(int num, int target){
Vector<int> values;
diceSumHelper(num, target, values);
}
void diceSumHelper(int num, int target, Vector<int> &values){
if(num == 0){
if(target == 0){
cout << values << endl;
}
} else{
for(int i=1;i<6+1;i++){
// Vector<int> tempValues = values;
// choose i
values.add(i);
// recursion
diceSumHelper(num-1, target-i, tempValues);
// what about the "unchoose" part?
// what does this mean?
values.removeBack();
}
}
}
// Helper1 goes through "ALL" possible cases.
void diceSumHelper2(int num, int target, Vector<int> &values){
if(num == 0){
if(target == 0){
cout << values << endl;
}
} else if (target >= num * 1 && target <= num*6){
for(int i=1;i<6+1;i++){
// Vector<int> tempValues = values;
// choose i
values.add(i);
// recursion
diceSumHelper(num-1, target-i, tempValues);
// what about the "unchoose" part?
values.removeBack();
}
}
}
<file_sep>/*
* CS 106B/X, <NAME>, <NAME>
* This file implements the GUI for the 8 Queens.
*/
#include "gui.h"
#include "console.h"
#include "gwindow.h"
#include "gobjects.h"
#include "gslider.h"
#include "glabel.h"
#include "map.h"
namespace GUI {
static const int kWindowSize = 600, kMargin = 30;
static GWindow* gWindow = nullptr;
static GSlider *gSpeedSlider = nullptr;
static GLabel *gLabel = nullptr;
static GPoint gUpperLeft;
static int gCellSize;
static Map<string, string> gColors {{"Q", "Black"}, {"?", "Red"}, {"⇧", "Blue"}};
static void delay();
static void drawCell(int row, int col, string s = "", bool outside = false);
void initialize(int dimension)
{
if (!gWindow) {
gWindow = new GWindow(kWindowSize, kWindowSize);
gWindow->setLocation(0, 0);
gWindow->setTitle("CS 106B/X Queens Demo");
gWindow->setResizable(false);
GObject::setAntiAliasing(false);
gWindow->setRepaintImmediately(false);
setConsoleLocation(0, kWindowSize + 75);
setConsoleSize(kWindowSize, 150);
gSpeedSlider = new GSlider(1, 10, 1);
double w = gWindow->getCanvasWidth();
gSpeedSlider->setBounds(w/4, 0, w/2, gSpeedSlider->getHeight());
gLabel = new GLabel("Click on board to step");
gWindow->addToRegion(gLabel, "SOUTH");
gWindow->addToRegion(gSpeedSlider, "SOUTH");
}
gCellSize = min((gWindow->getWidth() - kMargin)/(dimension+1), (gWindow->getHeight()- kMargin)/dimension);
gUpperLeft = {kMargin, kMargin};
int pointSize = gCellSize*.70;
gWindow->setFont("Helvetica-" + integerToString(pointSize));
for (int row = 0; row < dimension; row++) {
for (int col = 0; col < dimension; col++) {
drawCell(row, col);
}
}
gWindow->repaint();
gWindow->show();
}
static void delay()
{
gWindow->repaint();
// speed = 1 (wait for click) 2 slowest - 10 fastest
int speed = gSpeedSlider->getValue();
if (speed == 1) {
gLabel->setText("Click on board to step");
waitForClick();
} else {
gLabel->setText(" ");
if (speed != 10) {
pause(1000/speed);
}
}
}
static void drawCell(int row, int col, string label, bool outside)
{
double x = gUpperLeft.getX() + col*gCellSize + outside;
double y = gUpperLeft.getY() + row*gCellSize;
int alternating[] = {0xffffff, 0xcccccc};
int fill = outside ? alternating[0] : alternating[(row + col) % 2];
int border = outside ? alternating[0] : alternating[1];
gWindow->setColor(border);
gWindow->setFillColor(fill);
gWindow->fillRect(x, y, gCellSize , gCellSize);
if (!label.empty()) {
gWindow->setColor(gColors.containsKey(label) ? gColors[label] : "Black");
double delta = gCellSize/5;
gWindow->drawString(label, x + delta, y + delta*4);
}
}
void backtrack(int row, int col)
{
drawCell(row, col + 1, "⇧", true); // admittedly cheezy use of col + 1
delay();
drawCell(row, col + 1, "", true);
gWindow->repaint();
}
void consider(int row, int col)
{
drawCell(row, col, "?");
delay();
drawCell(row, col, "");
}
void occupy(int row, int col)
{
drawCell(row, col, "Q");
delay();
}
void leave(int row, int col)
{
drawCell(row, col, "");
gWindow->repaint();
}
void showSolution(Grid<bool> & board)
{
string what[] = {"", "Q", "", "Q","", "🏆", "Q"}; // blink board
int last = sizeof(what)/sizeof(*what) - 1;
for (int i = 0; i <= last; i++) {
for (int r = 0; r < board.numRows(); r++) {
for (int c = 0; c < board.numCols(); c++) {
string label = board[r][c] ? what[i] : "";
drawCell(r, c, label);
}
}
gWindow->repaint();
if (i == last-1) {
waitForClick();
} else {
pause(200);
}
}
}
} // end namespace
<file_sep>#include <iostream>
#include "console.h"
#include "gwindow.h" // for GWindow
#include "simpio.h" // for getLine
#include "vector.h" // for Vector
using namespace std;
struct ListNode{
int data;
ListNode* next;
};
void print(ListNode* node){
while(node != nullptr){
cout << node->data << endl;
node = node->next;
}
}
int main() {
// Two ways to declare an object
// (1) non-pointer;
/* Date d1;
* d1.month = 7;
* d1.day = 13;
*
* (2) pointer;
* Date* d2 = new Date();
* d2->month = 7;
* d2->day = 13;
*
* Arrow is a shorthand for: (*d2).month
*
* For #2, if you use it within a function, d2 is not "thrown away"
*/
ListNode* front = new ListNode();
front->data = 42;
front->next = new ListNode();
front->next->data = 32;
print(front);
print(front);
/* Note that when pointers are passed as arguments,
* the pointer is copied, so there is no need to
* make a copy of the pointer!
*
*
ListNode* tempNode = front;
while(tempNode != nullptr){
cout << tempNode->data << endl;
tempNode = tempNode->next;
}
*/
return 0;
}
<file_sep>#ifndef _ARRAYSTACK_H
#define _ARRAYSTACK_H
#include <iostream>
class ArrayStack{
public:
ArrayStack();
void push (int n);
int pop();
int peek();
bool isEmpty();
string toString();
private:
int* elements;
int size;
int capacity;
};
#endif // ARRAYSTACK_H
<file_sep>#include <iostream>
using namespace std;
struct TreeNode{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int data){
this->data = data;
}
TreeNode(int data, TreeNode* left, TreeNode* right){
this->data = data;
this->left = left;
this->right = right;
}
bool isLeaf(){
return (left == nullptr) && (right == nullptr);
}
};
void printTree(TreeNode* node){
if(node->right == nullptr && node->left == nullptr){
cout << node->data << endl;
} else{
printTree(node->right);
printTree(node->left);
}
/*
if(node != nullptr){
cout << node->data << endl;
printTree(node->right);
printTree(node->left);
}
*/
}
int sizeTree(TreeNode* node){
if(node == nullptr){
return 0;
}
return 1 + sizeTree(node->right) + sizeTree(node->left);
}
bool contains(TreeNode *node, int value){
if(node == nullptr){
return false;
} else if(node->data == value){
return true;
} else{
return contains(node->right, value) || contains(node->right, value);
}
}
int main(){
TreeNode* root = new TreeNode(2)
printTree(root);
return 0;
}<file_sep>/*
* CS 106B/X, <NAME>, <NAME>
* This file declares the GUI for 8 Queens demo.
*/
#ifndef _gui_h
#define _gui_h
#include "gwindow.h"
#include "grid.h"
using namespace std;
namespace GUI {
void initialize(int dimension);
void consider(int row, int col);
void occupy(int row, int col);
void leave(int row, int col);
void backtrack(int row, int col);
void showSolution(Grid<bool> &board);
} // end namespace
#endif
<file_sep>#include "BankAccount.h"
// The Constructor
BankAccount::BankAccount(std::string name, double initDepoist){
this->name = name;
this->balance = initDepoist;
}
BankAccount::deposit(double amount){
if(amount > 0){
this->balance += amount;
}
}
BankAccount::withdraw(double amount){
if(amount <= depoist){
this->balance = this->balance - amount;
}
}
<file_sep>#include <iostream>
#include "basicgraph.h"
using namespace std;
string coolest(istream& input){
// reading the line
BasicGraph graph;
string name1, name2;
while(input >> name1 >> name2){
graph.addVertex(name1);
graph.addVertex(name2);
graph.addEdge(name1, name2);
}
cout << graph << endl;
// who has the most followers of followers?
int maxFof = 0;
string coolest = "-";
for(string v: graph.getVertexNames()){
int fof = 0;
for(string neighbor : graph.getNeighborNames(v)){
fof += graph.getNeighborNames(neighbor).size();
}
if(fof > maxfof){
maxFof = fof;
coolest = v;
}
}
return coolest;
}
int main() {
return 0;
}
<file_sep>// This is the CPP file you will edit and turn in. (TODO: Remove this comment!)
#include "LinkedListPatientQueue.h"
#include <sstream>
LinkedListPatientQueue::LinkedListPatientQueue() {
front = nullptr;
}
LinkedListPatientQueue::~LinkedListPatientQueue() {
PatientNode* temp = front;
while(temp != nullptr){
PatientNode* current = temp;
delete(current);
temp = temp->next;
}
}
void LinkedListPatientQueue::clear() {
while(front != nullptr){
PatientNode *temp = front;
front = front->next;
delete(temp);
}
}
string LinkedListPatientQueue::frontName() {
if(isEmpty()){
throw "Patient Queue is Empty!";
} else{
return front->name;
}
}
int LinkedListPatientQueue::frontPriority() {
if(isEmpty()){
throw "Patient Queue is Empty!";
} else{
return front->priority;
}
}
bool LinkedListPatientQueue::isEmpty() {
return (front == nullptr);
}
void LinkedListPatientQueue::newPatient(string name, int priority) {
PatientNode *temp = new PatientNode(name, priority, nullptr);
// no element in list
if(front == nullptr){
front = temp;
} else{
PatientNode *index = front;
while(index != nullptr){
if(index->priority <= priority &&
(index->next == nullptr || index->next->priority > priority)){
break;
} else{
index = index->next;
}
}
// insert new node next to index.
temp->next = index->next;
index->next = temp;
}
}
string LinkedListPatientQueue::processPatient() {
if(front == nullptr){
throw "PatientQueue is empty.";
} else{
PatientNode *temp = front;
string name = temp->name;
front = front->next;
delete(temp);
return name;
}
}
void LinkedListPatientQueue::upgradePatient(string name, int newPriority) {
PatientNode *temp = front;
while(temp != nullptr){
if(temp->name == name){
temp->priority = newPriority;
break;
}
temp = temp->next;
}
// if no such patient is found
if(temp == nullptr){
throw "No such patient exists";
}
}
string LinkedListPatientQueue::toString() {
PatientNode *temp = front;
stringstream s;
s << "{";
while(temp != nullptr){
s << temp->priority << ":" << temp->name;
if(temp->next != nullptr){
s << ", ";
}
temp = temp->next;
}
s << "}";
return s.str(); // this is only here so it will compile
}
<file_sep>// This is the CPP file you will edit and turn in. (TODO: Remove this comment!)
#include "VectorPatientQueue.h"
#include <sstream>
VectorPatientQueue::VectorPatientQueue() {
}
VectorPatientQueue::~VectorPatientQueue() {
//DO NOTHING
}
void VectorPatientQueue::clear() {
pq.clear();
}
string VectorPatientQueue::frontName() {
if(pq.isEmpty()){
throw "patient queue is empty";
} else{
int tempTimestamp = INT_FAST8_MAX;
int highestPriority = frontPriority();
int index;
for(int i=0;i<pq.size();i++){
if(pq[i].priority == highestPriority){
if(pq[i].timestamp < tempTimestamp){
tempTimestamp = pq[i].timestamp;
index = i;
}
}
}
return pq[index].name;
}
}
int VectorPatientQueue::frontPriority() {
if(pq.isEmpty()){
throw "patient queue is empty";
} else{
int tempPriority = INT_FAST8_MAX;
for(int i=0;i<pq.size();i++){
if(pq[i].priority < tempPriority){
tempPriority = pq[i].priority;
}
}
return tempPriority;
}
}
bool VectorPatientQueue::isEmpty() {
return pq.isEmpty();
}
void VectorPatientQueue::newPatient(string name, int priority) {
Patient temp(name, priority, timeCounter++);
pq.add(temp);
}
string VectorPatientQueue::processPatient() {
if(pq.isEmpty()){
throw "patient queue is empty";
} else{
string patientName = frontName();
// get index of lowest priority patient
int tempTimestamp = INT_FAST8_MAX;
int highestPriority = frontPriority();
int index;
for(int i=0;i<pq.size();i++){
if(pq[i].priority == highestPriority){
if(pq[i].timestamp < tempTimestamp){
tempTimestamp = pq[i].timestamp;
index = i;
}
}
}
// remove patient of highest priority.
pq.remove(index);
return patientName;
}
// TODO: write this function
return ""; // this is only here so it will compile
}
void VectorPatientQueue::upgradePatient(string name, int newPriority) {
int tempTimestamp = INT_FAST8_MAX;
int index = -1;
for(int i=0;i<pq.size();i++){
if(pq[i].name == name){
if(pq[i].timestamp < tempTimestamp){
tempTimestamp = pq[i].timestamp;
index = i;
}
}
}
// if there is no such patient, throw an exception
if(index == -1){
throw "No such Patient Exists";
}
// check for exception
if(pq[index].priority < newPriority){
throw "patient already has higher priority";
} else{
pq[index].priority = newPriority;
}
}
string VectorPatientQueue::toString() {
stringstream s;
s << "{";
for(int i=0;i<pq.size();i++){
s << pq[i].priority << ":" << pq[i].name;
if(i != pq.size()-1){
s << ", ";
}
}
s << "}";
return s.str();
}
<file_sep>#include <iostream>
#include "console.h"
#include "gwindow.h" // for GWindow
#include "simpio.h" // for getLine
#include "vector.h" // for Vector
using namespace std;
/*
ostream& operator <<(ostream& out, Type& name){
statements;
return out;
}
*/
int main() {
return 0;
}
<file_sep>#############################################################################
# Makefile for building: Huffman
# Generated by qmake (3.1) (Qt 5.9.5)
# Project: ../Huffman/Huffman.pro
# Template: app
# Command: /usr/lib/qt5/bin/qmake -o Makefile ../Huffman/Huffman.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
#############################################################################
MAKEFILE = Makefile
####### Compiler, tools and options
CC = gcc
CXX = g++
DEFINES = -DSPL_PROJECT_VERSION=20171115 -DSPL_CONSOLE_X=-1 -DSPL_CONSOLE_Y=-1 -DSPL_CONSOLE_WIDTH=800 -DSPL_CONSOLE_HEIGHT=500 -DSPL_CONSOLE_ECHO -DSPL_CONSOLE_EXIT_ON_CLOSE -DSPL_VERIFY_JAVA_BACKEND_VERSION -DSPL_VERIFY_PROJECT_VERSION -DPQUEUE_ALLOW_HEAP_ACCESS -DPQUEUE_PRINT_IN_HEAP_ORDER -DSPL_THROW_ON_INVALID_ITERATOR -DSPL_CONSOLE_PRINT_EXCEPTIONS -DQT_QML_DEBUG
CFLAGS = -pipe -g -Wall -W -fPIC $(DEFINES)
CXXFLAGS = -pipe -Wall -Wextra -Wcast-align -Wfloat-equal -Wformat=2 -Wlogical-op -Wlong-long -Wno-missing-field-initializers -Wno-sign-compare -Wno-sign-conversion -Wno-write-strings -Wreturn-type -Werror=return-type -Werror=uninitialized -Wunreachable-code -Wuseless-cast -Wno-unused-const-variable -g3 -fno-inline -fno-omit-frame-pointer -g -std=gnu++11 -Wall -W -fPIC $(DEFINES)
INCPATH = -I../Huffman/lib/StanfordCPPLib -I../Huffman/lib/StanfordCPPLib/collections -I../Huffman/lib/StanfordCPPLib/graphics -I../Huffman/lib/StanfordCPPLib/io -I../Huffman/lib/StanfordCPPLib/system -I../Huffman/lib/StanfordCPPLib/util -I../Huffman/src -I../Huffman -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++
QMAKE = /usr/lib/qt5/bin/qmake
DEL_FILE = rm -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p
COPY = cp -f
COPY_FILE = cp -f
COPY_DIR = cp -f -R
INSTALL_FILE = install -m 644 -p
INSTALL_PROGRAM = install -m 755 -p
INSTALL_DIR = cp -f -R
QINSTALL = /usr/lib/qt5/bin/qmake -install qinstall
QINSTALL_PROGRAM = /usr/lib/qt5/bin/qmake -install qinstall -exe
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
TAR = tar -cf
COMPRESS = gzip -9f
DISTNAME = Huffman1.0.0
DISTDIR = /tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug/.tmp/Huffman1.0.0
LINK = g++
LFLAGS = -rdynamic -Wl,--export-dynamic
LIBS = $(SUBLIBS) -ldl -lpthread
AR = ar cqs
RANLIB =
SED = sed
STRIP = strip
####### Output directory
OBJECTS_DIR = ./
####### Files
SOURCES = ../Huffman/lib/StanfordCPPLib/collections/basicgraph.cpp \
../Huffman/lib/StanfordCPPLib/collections/dawglexicon.cpp \
../Huffman/lib/StanfordCPPLib/collections/hashcode.cpp \
../Huffman/lib/StanfordCPPLib/collections/lexicon.cpp \
../Huffman/lib/StanfordCPPLib/collections/shuffle.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gevents.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gfilechooser.cpp \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.cpp \
../Huffman/lib/StanfordCPPLib/graphics/goptionpane.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtable.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtextarea.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.cpp \
../Huffman/lib/StanfordCPPLib/io/base64.cpp \
../Huffman/lib/StanfordCPPLib/io/bitstream.cpp \
../Huffman/lib/StanfordCPPLib/io/console.cpp \
../Huffman/lib/StanfordCPPLib/io/filelib.cpp \
../Huffman/lib/StanfordCPPLib/io/plainconsole.cpp \
../Huffman/lib/StanfordCPPLib/io/server.cpp \
../Huffman/lib/StanfordCPPLib/io/simpio.cpp \
../Huffman/lib/StanfordCPPLib/io/tokenscanner.cpp \
../Huffman/lib/StanfordCPPLib/io/urlstream.cpp \
../Huffman/lib/StanfordCPPLib/private/platform.cpp \
../Huffman/lib/StanfordCPPLib/private/tplatform_posix.cpp \
../Huffman/lib/StanfordCPPLib/private/version.cpp \
../Huffman/lib/StanfordCPPLib/system/call_stack_gcc.cpp \
../Huffman/lib/StanfordCPPLib/system/call_stack_windows.cpp \
../Huffman/lib/StanfordCPPLib/system/error.cpp \
../Huffman/lib/StanfordCPPLib/system/exceptions.cpp \
../Huffman/lib/StanfordCPPLib/system/process.cpp \
../Huffman/lib/StanfordCPPLib/system/thread.cpp \
../Huffman/lib/StanfordCPPLib/util/bigfloat.cpp \
../Huffman/lib/StanfordCPPLib/util/biginteger.cpp \
../Huffman/lib/StanfordCPPLib/util/complex.cpp \
../Huffman/lib/StanfordCPPLib/util/direction.cpp \
../Huffman/lib/StanfordCPPLib/util/gmath.cpp \
../Huffman/lib/StanfordCPPLib/util/note.cpp \
../Huffman/lib/StanfordCPPLib/util/observable.cpp \
../Huffman/lib/StanfordCPPLib/util/point.cpp \
../Huffman/lib/StanfordCPPLib/util/random.cpp \
../Huffman/lib/StanfordCPPLib/util/recursion.cpp \
../Huffman/lib/StanfordCPPLib/util/regexpr.cpp \
../Huffman/lib/StanfordCPPLib/util/sound.cpp \
../Huffman/lib/StanfordCPPLib/util/strlib.cpp \
../Huffman/lib/StanfordCPPLib/util/timer.cpp \
../Huffman/src/encoding.cpp \
../Huffman/src/huffmanmain.cpp \
../Huffman/src/HuffmanNode.cpp \
../Huffman/src/huffmanutil.cpp \
../Huffman/src/mymap.cpp
OBJECTS = basicgraph.o \
dawglexicon.o \
hashcode.o \
lexicon.o \
shuffle.o \
gbufferedimage.o \
gevents.o \
gfilechooser.o \
ginteractors.o \
gobjects.o \
goptionpane.o \
gtable.o \
gtextarea.o \
gtimer.o \
gtypes.o \
gwindow.o \
base64.o \
bitstream.o \
console.o \
filelib.o \
plainconsole.o \
server.o \
simpio.o \
tokenscanner.o \
urlstream.o \
platform.o \
tplatform_posix.o \
version.o \
call_stack_gcc.o \
call_stack_windows.o \
error.o \
exceptions.o \
process.o \
thread.o \
bigfloat.o \
biginteger.o \
complex.o \
direction.o \
gmath.o \
note.o \
observable.o \
point.o \
random.o \
recursion.o \
regexpr.o \
sound.o \
strlib.o \
timer.o \
encoding.o \
huffmanmain.o \
HuffmanNode.o \
huffmanutil.o \
mymap.o
DIST = /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \
../Huffman/Huffman.pro /tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/basicgraph.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/collections.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/dawglexicon.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/deque.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/graph.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/grid.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/hashcode.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/hashmap.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/hashset.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/lexicon.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/linkedhashmap.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/linkedhashset.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/linkedlist.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/map.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/pqueue.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/priorityqueue.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/queue.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/set.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/shuffle.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/sparsegrid.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/stack.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/stl.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/collections/vector.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gevents.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gfilechooser.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/goptionpane.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gtable.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gtextarea.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/base64.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/bitstream.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/console.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/filelib.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/plainconsole.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/server.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/simpio.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/tokenscanner.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/io/urlstream.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/consolestreambuf.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/echoinputstreambuf.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/foreachpatch.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/forwardingstreambuf.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/init.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/limitoutputstreambuf.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/platform.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/randompatch.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/static.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/tokenpatch.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/tplatform.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/private/version.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/call_stack.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/error.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/exceptions.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/process.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/pstream.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/stack_exception.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/system/thread.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/bigfloat.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/biginteger.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/complex.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/direction.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/foreach.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/gmath.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/note.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/observable.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/point.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/random.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/recursion.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/regexpr.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/sound.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/strlib.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/StanfordCPPLib/util/timer.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/src/encoding.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/src/HuffmanNode.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/src/huffmanutil.h \
/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/src/mymap.h ../Huffman/lib/StanfordCPPLib/collections/basicgraph.cpp \
../Huffman/lib/StanfordCPPLib/collections/dawglexicon.cpp \
../Huffman/lib/StanfordCPPLib/collections/hashcode.cpp \
../Huffman/lib/StanfordCPPLib/collections/lexicon.cpp \
../Huffman/lib/StanfordCPPLib/collections/shuffle.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gevents.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gfilechooser.cpp \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.cpp \
../Huffman/lib/StanfordCPPLib/graphics/goptionpane.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtable.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtextarea.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.cpp \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.cpp \
../Huffman/lib/StanfordCPPLib/io/base64.cpp \
../Huffman/lib/StanfordCPPLib/io/bitstream.cpp \
../Huffman/lib/StanfordCPPLib/io/console.cpp \
../Huffman/lib/StanfordCPPLib/io/filelib.cpp \
../Huffman/lib/StanfordCPPLib/io/plainconsole.cpp \
../Huffman/lib/StanfordCPPLib/io/server.cpp \
../Huffman/lib/StanfordCPPLib/io/simpio.cpp \
../Huffman/lib/StanfordCPPLib/io/tokenscanner.cpp \
../Huffman/lib/StanfordCPPLib/io/urlstream.cpp \
../Huffman/lib/StanfordCPPLib/private/platform.cpp \
../Huffman/lib/StanfordCPPLib/private/tplatform_posix.cpp \
../Huffman/lib/StanfordCPPLib/private/version.cpp \
../Huffman/lib/StanfordCPPLib/system/call_stack_gcc.cpp \
../Huffman/lib/StanfordCPPLib/system/call_stack_windows.cpp \
../Huffman/lib/StanfordCPPLib/system/error.cpp \
../Huffman/lib/StanfordCPPLib/system/exceptions.cpp \
../Huffman/lib/StanfordCPPLib/system/process.cpp \
../Huffman/lib/StanfordCPPLib/system/thread.cpp \
../Huffman/lib/StanfordCPPLib/util/bigfloat.cpp \
../Huffman/lib/StanfordCPPLib/util/biginteger.cpp \
../Huffman/lib/StanfordCPPLib/util/complex.cpp \
../Huffman/lib/StanfordCPPLib/util/direction.cpp \
../Huffman/lib/StanfordCPPLib/util/gmath.cpp \
../Huffman/lib/StanfordCPPLib/util/note.cpp \
../Huffman/lib/StanfordCPPLib/util/observable.cpp \
../Huffman/lib/StanfordCPPLib/util/point.cpp \
../Huffman/lib/StanfordCPPLib/util/random.cpp \
../Huffman/lib/StanfordCPPLib/util/recursion.cpp \
../Huffman/lib/StanfordCPPLib/util/regexpr.cpp \
../Huffman/lib/StanfordCPPLib/util/sound.cpp \
../Huffman/lib/StanfordCPPLib/util/strlib.cpp \
../Huffman/lib/StanfordCPPLib/util/timer.cpp \
../Huffman/src/encoding.cpp \
../Huffman/src/huffmanmain.cpp \
../Huffman/src/HuffmanNode.cpp \
../Huffman/src/huffmanutil.cpp \
../Huffman/src/mymap.cpp
QMAKE_TARGET = Huffman
DESTDIR =
TARGET = Huffman
first: all
####### Build rules
$(TARGET): $(OBJECTS) copyResources
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)
Makefile: ../Huffman/Huffman.pro .qmake.cache /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \
../Huffman/Huffman.pro
$(QMAKE) -o Makefile ../Huffman/Huffman.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf:
../Huffman/Huffman.pro:
qmake: FORCE
@$(QMAKE) -o Makefile ../Huffman/Huffman.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
qmake_all: FORCE
all: Makefile $(TARGET)
dist: distdir FORCE
(cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR)
distdir: FORCE
@test -d $(DISTDIR) || mkdir -p $(DISTDIR)
$(COPY_FILE) --parents $(DIST) $(DISTDIR)/
clean: compiler_clean
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) *~ core *.core
distclean: clean
-$(DEL_FILE) $(TARGET)
-$(DEL_FILE) .qmake.stash
-$(DEL_FILE) Makefile
####### Sub-libraries
copyResources:
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/ababcab.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/allcharsonce.dat" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/alphaonce.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/alphatwice.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/as.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/asciiart.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/bender.jpg" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/dictionary.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/empty.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/example.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/example2.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/excellent.wav" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/fibonacci.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/hamlet.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/hellokitty.bmp" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/large.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/larger.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/medium.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/moo.wav" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/nonrepeated.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/poem.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/secretmessage.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/short.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/singlechar.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/res/tomsawyer.txt" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
cp -rf "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/Huffman/lib/spl.jar" "/tmp/guest-y6dsre/Desktop/CS106B-Stanford/Assignment-Code/Assignment06/build-Huffman-Desktop-Debug"
first:
copydata:
check: first
benchmark: first
compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean:
####### Compile
basicgraph.o: ../Huffman/lib/StanfordCPPLib/collections/basicgraph.cpp ../Huffman/lib/StanfordCPPLib/collections/basicgraph.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/collections/graph.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/set.h \
../Huffman/lib/StanfordCPPLib/io/tokenscanner.h \
../Huffman/lib/StanfordCPPLib/private/tokenpatch.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/util/observable.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o basicgraph.o ../Huffman/lib/StanfordCPPLib/collections/basicgraph.cpp
dawglexicon.o: ../Huffman/lib/StanfordCPPLib/collections/dawglexicon.cpp ../Huffman/lib/StanfordCPPLib/collections/dawglexicon.h \
../Huffman/lib/StanfordCPPLib/collections/set.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o dawglexicon.o ../Huffman/lib/StanfordCPPLib/collections/dawglexicon.cpp
hashcode.o: ../Huffman/lib/StanfordCPPLib/collections/hashcode.cpp ../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o hashcode.o ../Huffman/lib/StanfordCPPLib/collections/hashcode.cpp
lexicon.o: ../Huffman/lib/StanfordCPPLib/collections/lexicon.cpp ../Huffman/lib/StanfordCPPLib/collections/lexicon.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/collections/set.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/dawglexicon.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o lexicon.o ../Huffman/lib/StanfordCPPLib/collections/lexicon.cpp
shuffle.o: ../Huffman/lib/StanfordCPPLib/collections/shuffle.cpp ../Huffman/lib/StanfordCPPLib/collections/shuffle.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o shuffle.o ../Huffman/lib/StanfordCPPLib/collections/shuffle.cpp
gbufferedimage.o: ../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.cpp ../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/io/base64.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gbufferedimage.o ../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.cpp
gevents.o: ../Huffman/lib/StanfordCPPLib/graphics/gevents.cpp ../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gevents.o ../Huffman/lib/StanfordCPPLib/graphics/gevents.cpp
gfilechooser.o: ../Huffman/lib/StanfordCPPLib/graphics/gfilechooser.cpp ../Huffman/lib/StanfordCPPLib/graphics/gfilechooser.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gfilechooser.o ../Huffman/lib/StanfordCPPLib/graphics/gfilechooser.cpp
ginteractors.o: ../Huffman/lib/StanfordCPPLib/graphics/ginteractors.cpp ../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o ginteractors.o ../Huffman/lib/StanfordCPPLib/graphics/ginteractors.cpp
gobjects.o: ../Huffman/lib/StanfordCPPLib/graphics/gobjects.cpp ../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gobjects.o ../Huffman/lib/StanfordCPPLib/graphics/gobjects.cpp
goptionpane.o: ../Huffman/lib/StanfordCPPLib/graphics/goptionpane.cpp ../Huffman/lib/StanfordCPPLib/graphics/goptionpane.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o goptionpane.o ../Huffman/lib/StanfordCPPLib/graphics/goptionpane.cpp
gtable.o: ../Huffman/lib/StanfordCPPLib/graphics/gtable.cpp ../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtable.o ../Huffman/lib/StanfordCPPLib/graphics/gtable.cpp
gtextarea.o: ../Huffman/lib/StanfordCPPLib/graphics/gtextarea.cpp ../Huffman/lib/StanfordCPPLib/graphics/gtextarea.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/io/base64.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtextarea.o ../Huffman/lib/StanfordCPPLib/graphics/gtextarea.cpp
gtimer.o: ../Huffman/lib/StanfordCPPLib/graphics/gtimer.cpp ../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtimer.o ../Huffman/lib/StanfordCPPLib/graphics/gtimer.cpp
gtypes.o: ../Huffman/lib/StanfordCPPLib/graphics/gtypes.cpp ../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtypes.o ../Huffman/lib/StanfordCPPLib/graphics/gtypes.cpp
gwindow.o: ../Huffman/lib/StanfordCPPLib/graphics/gwindow.cpp ../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gwindow.o ../Huffman/lib/StanfordCPPLib/graphics/gwindow.cpp
base64.o: ../Huffman/lib/StanfordCPPLib/io/base64.cpp ../Huffman/lib/StanfordCPPLib/io/base64.h \
../Huffman/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o base64.o ../Huffman/lib/StanfordCPPLib/io/base64.cpp
bitstream.o: ../Huffman/lib/StanfordCPPLib/io/bitstream.cpp ../Huffman/lib/StanfordCPPLib/io/bitstream.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o bitstream.o ../Huffman/lib/StanfordCPPLib/io/bitstream.cpp
console.o: ../Huffman/lib/StanfordCPPLib/io/console.cpp ../Huffman/lib/StanfordCPPLib/io/console.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/system/exceptions.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o console.o ../Huffman/lib/StanfordCPPLib/io/console.cpp
filelib.o: ../Huffman/lib/StanfordCPPLib/io/filelib.cpp ../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/io/simpio.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o filelib.o ../Huffman/lib/StanfordCPPLib/io/filelib.cpp
plainconsole.o: ../Huffman/lib/StanfordCPPLib/io/plainconsole.cpp ../Huffman/lib/StanfordCPPLib/io/plainconsole.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o plainconsole.o ../Huffman/lib/StanfordCPPLib/io/plainconsole.cpp
server.o: ../Huffman/lib/StanfordCPPLib/io/server.cpp ../Huffman/lib/StanfordCPPLib/io/server.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o server.o ../Huffman/lib/StanfordCPPLib/io/server.cpp
simpio.o: ../Huffman/lib/StanfordCPPLib/io/simpio.cpp ../Huffman/lib/StanfordCPPLib/io/simpio.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o simpio.o ../Huffman/lib/StanfordCPPLib/io/simpio.cpp
tokenscanner.o: ../Huffman/lib/StanfordCPPLib/io/tokenscanner.cpp ../Huffman/lib/StanfordCPPLib/io/tokenscanner.h \
../Huffman/lib/StanfordCPPLib/private/tokenpatch.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/util/random.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o tokenscanner.o ../Huffman/lib/StanfordCPPLib/io/tokenscanner.cpp
urlstream.o: ../Huffman/lib/StanfordCPPLib/io/urlstream.cpp ../Huffman/lib/StanfordCPPLib/io/urlstream.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o urlstream.o ../Huffman/lib/StanfordCPPLib/io/urlstream.cpp
platform.o: ../Huffman/lib/StanfordCPPLib/private/platform.cpp ../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/consolestreambuf.h \
../Huffman/lib/StanfordCPPLib/private/forwardingstreambuf.h \
../Huffman/lib/StanfordCPPLib/private/static.h \
../Huffman/lib/StanfordCPPLib/private/version.h \
../Huffman/lib/StanfordCPPLib/io/base64.h \
../Huffman/lib/StanfordCPPLib/io/console.h \
../Huffman/lib/StanfordCPPLib/system/exceptions.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../Huffman/lib/StanfordCPPLib/collections/hashmap.h \
../Huffman/lib/StanfordCPPLib/collections/queue.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/io/tokenscanner.h \
../Huffman/lib/StanfordCPPLib/private/tokenpatch.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o platform.o ../Huffman/lib/StanfordCPPLib/private/platform.cpp
tplatform_posix.o: ../Huffman/lib/StanfordCPPLib/private/tplatform_posix.cpp ../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/private/tplatform.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o tplatform_posix.o ../Huffman/lib/StanfordCPPLib/private/tplatform_posix.cpp
version.o: ../Huffman/lib/StanfordCPPLib/private/version.cpp ../Huffman/lib/StanfordCPPLib/private/version.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o version.o ../Huffman/lib/StanfordCPPLib/private/version.cpp
call_stack_gcc.o: ../Huffman/lib/StanfordCPPLib/system/call_stack_gcc.cpp ../Huffman/lib/StanfordCPPLib/system/call_stack.h \
../Huffman/lib/StanfordCPPLib/system/exceptions.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o call_stack_gcc.o ../Huffman/lib/StanfordCPPLib/system/call_stack_gcc.cpp
call_stack_windows.o: ../Huffman/lib/StanfordCPPLib/system/call_stack_windows.cpp ../Huffman/lib/StanfordCPPLib/system/call_stack.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/exceptions.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o call_stack_windows.o ../Huffman/lib/StanfordCPPLib/system/call_stack_windows.cpp
error.o: ../Huffman/lib/StanfordCPPLib/system/error.cpp ../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/exceptions.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o error.o ../Huffman/lib/StanfordCPPLib/system/error.cpp
exceptions.o: ../Huffman/lib/StanfordCPPLib/system/exceptions.cpp ../Huffman/lib/StanfordCPPLib/system/exceptions.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/call_stack.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/static.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o exceptions.o ../Huffman/lib/StanfordCPPLib/system/exceptions.cpp
process.o: ../Huffman/lib/StanfordCPPLib/system/process.cpp ../Huffman/lib/StanfordCPPLib/system/process.h \
../Huffman/lib/StanfordCPPLib/system/pstream.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o process.o ../Huffman/lib/StanfordCPPLib/system/process.cpp
thread.o: ../Huffman/lib/StanfordCPPLib/system/thread.cpp ../Huffman/lib/StanfordCPPLib/system/thread.h \
../Huffman/lib/StanfordCPPLib/private/tplatform.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o thread.o ../Huffman/lib/StanfordCPPLib/system/thread.cpp
bigfloat.o: ../Huffman/lib/StanfordCPPLib/util/bigfloat.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o bigfloat.o ../Huffman/lib/StanfordCPPLib/util/bigfloat.cpp
biginteger.o: ../Huffman/lib/StanfordCPPLib/util/biginteger.cpp ../Huffman/lib/StanfordCPPLib/util/biginteger.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o biginteger.o ../Huffman/lib/StanfordCPPLib/util/biginteger.cpp
complex.o: ../Huffman/lib/StanfordCPPLib/util/complex.cpp ../Huffman/lib/StanfordCPPLib/util/complex.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o complex.o ../Huffman/lib/StanfordCPPLib/util/complex.cpp
direction.o: ../Huffman/lib/StanfordCPPLib/util/direction.cpp ../Huffman/lib/StanfordCPPLib/util/direction.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/io/tokenscanner.h \
../Huffman/lib/StanfordCPPLib/private/tokenpatch.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o direction.o ../Huffman/lib/StanfordCPPLib/util/direction.cpp
gmath.o: ../Huffman/lib/StanfordCPPLib/util/gmath.cpp ../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gmath.o ../Huffman/lib/StanfordCPPLib/util/gmath.cpp
note.o: ../Huffman/lib/StanfordCPPLib/util/note.cpp ../Huffman/lib/StanfordCPPLib/util/note.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o note.o ../Huffman/lib/StanfordCPPLib/util/note.cpp
observable.o: ../Huffman/lib/StanfordCPPLib/util/observable.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o observable.o ../Huffman/lib/StanfordCPPLib/util/observable.cpp
point.o: ../Huffman/lib/StanfordCPPLib/util/point.cpp ../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o point.o ../Huffman/lib/StanfordCPPLib/util/point.cpp
random.o: ../Huffman/lib/StanfordCPPLib/util/random.cpp ../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o random.o ../Huffman/lib/StanfordCPPLib/util/random.cpp
recursion.o: ../Huffman/lib/StanfordCPPLib/util/recursion.cpp ../Huffman/lib/StanfordCPPLib/util/recursion.h \
../Huffman/lib/StanfordCPPLib/system/exceptions.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/call_stack.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o recursion.o ../Huffman/lib/StanfordCPPLib/util/recursion.cpp
regexpr.o: ../Huffman/lib/StanfordCPPLib/util/regexpr.cpp ../Huffman/lib/StanfordCPPLib/util/regexpr.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h \
../Huffman/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o regexpr.o ../Huffman/lib/StanfordCPPLib/util/regexpr.cpp
sound.o: ../Huffman/lib/StanfordCPPLib/util/sound.cpp ../Huffman/lib/StanfordCPPLib/util/sound.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/private/platform.h \
../Huffman/lib/StanfordCPPLib/graphics/gevents.h \
../Huffman/lib/StanfordCPPLib/graphics/gtable.h \
../Huffman/lib/StanfordCPPLib/collections/grid.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/graphics/ginteractors.h \
../Huffman/lib/StanfordCPPLib/graphics/gobjects.h \
../Huffman/lib/StanfordCPPLib/graphics/gwindow.h \
../Huffman/lib/StanfordCPPLib/util/point.h \
../Huffman/lib/StanfordCPPLib/graphics/gtimer.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o sound.o ../Huffman/lib/StanfordCPPLib/util/sound.cpp
strlib.o: ../Huffman/lib/StanfordCPPLib/util/strlib.cpp ../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o strlib.o ../Huffman/lib/StanfordCPPLib/util/strlib.cpp
timer.o: ../Huffman/lib/StanfordCPPLib/util/timer.cpp ../Huffman/lib/StanfordCPPLib/util/timer.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o timer.o ../Huffman/lib/StanfordCPPLib/util/timer.cpp
encoding.o: ../Huffman/src/encoding.cpp ../Huffman/src/encoding.h \
../Huffman/lib/StanfordCPPLib/io/bitstream.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/src/HuffmanNode.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/queue.h \
../Huffman/lib/StanfordCPPLib/collections/pqueue.h \
../Huffman/lib/StanfordCPPLib/collections/priorityqueue.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o encoding.o ../Huffman/src/encoding.cpp
huffmanmain.o: ../Huffman/src/huffmanmain.cpp ../Huffman/lib/StanfordCPPLib/io/console.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/io/simpio.h \
../Huffman/src/HuffmanNode.h \
../Huffman/lib/StanfordCPPLib/io/bitstream.h \
../Huffman/src/encoding.h \
../Huffman/lib/StanfordCPPLib/collections/map.h \
../Huffman/lib/StanfordCPPLib/collections/stack.h \
../Huffman/lib/StanfordCPPLib/collections/queue.h \
../Huffman/src/huffmanutil.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o huffmanmain.o ../Huffman/src/huffmanmain.cpp
HuffmanNode.o: ../Huffman/src/HuffmanNode.cpp ../Huffman/src/HuffmanNode.h \
../Huffman/lib/StanfordCPPLib/io/bitstream.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/src/huffmanutil.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o HuffmanNode.o ../Huffman/src/HuffmanNode.cpp
huffmanutil.o: ../Huffman/src/huffmanutil.cpp ../Huffman/src/huffmanutil.h \
../Huffman/lib/StanfordCPPLib/io/bitstream.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/io/filelib.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h \
../Huffman/lib/StanfordCPPLib/io/simpio.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o huffmanutil.o ../Huffman/src/huffmanutil.cpp
mymap.o: ../Huffman/src/mymap.cpp ../Huffman/src/mymap.h \
../Huffman/lib/StanfordCPPLib/collections/vector.h \
../Huffman/lib/StanfordCPPLib/collections/collections.h \
../Huffman/lib/StanfordCPPLib/system/error.h \
../Huffman/lib/StanfordCPPLib/private/init.h \
../Huffman/lib/StanfordCPPLib/util/gmath.h \
../Huffman/lib/StanfordCPPLib/graphics/gtypes.h \
../Huffman/lib/StanfordCPPLib/collections/hashcode.h \
../Huffman/lib/StanfordCPPLib/util/random.h \
../Huffman/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o mymap.o ../Huffman/src/mymap.cpp
####### Install
install: FORCE
uninstall: FORCE
FORCE:
<file_sep>#include <iostream>
using namespace std;
struct TreeNode{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int data){
this->data = data;
}
TreeNode(int data, TreeNode* left, TreeNode* right){
this->data = data;
this->left = left;
this->right = right;
}
bool isLeaf(){
return (left == nullptr) && (right == nullptr);
}
};
<file_sep>#include <string>
class Soldier{
public:
Soldier(std::string, std::string);
~Soldier();
std::string getName() const;
std::string getStartDate() const;
std::string getEndDate() const;
private:
std::string name;
std::string startDate;
std::string endDate;
string calculateEndDate();
void setStartDate(std::string);
void setEndDate();
};<file_sep>// This is the H file you will edit and turn in. (TODO: Remove this comment!)
#pragma once
#include <iostream>
#include <string>
#include "vector.h"
#include "patientqueue.h"
using namespace std;
// struct for patient
struct Patient{
public:
string name;
int priority;
int timestamp;
Patient(){}
Patient(string name, int priority, int timestamp){
this->name = name;
this->priority = priority;
this->timestamp = timestamp;
}
};
class VectorPatientQueue : public PatientQueue {
public:
VectorPatientQueue();
~VectorPatientQueue();
string frontName();
void clear();
int frontPriority();
bool isEmpty();
void newPatient(string name, int priority);
string processPatient();
void upgradePatient(string name, int newPriority);
string toString();
private:
Vector<Patient> pq;
int timeCounter = 0;
};
<file_sep>#############################################################################
# Makefile for building: GrammarSolver
# Generated by qmake (3.1) (Qt 5.9.5)
# Project: ../GrammarSolver/GrammarSolver.pro
# Template: app
# Command: /usr/lib/qt5/bin/qmake -o Makefile ../GrammarSolver/GrammarSolver.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
#############################################################################
MAKEFILE = Makefile
####### Compiler, tools and options
CC = gcc
CXX = g++
DEFINES = -DSPL_PROJECT_VERSION=20171115 -DSPL_CONSOLE_X=-1 -DSPL_CONSOLE_Y=-1 -DSPL_CONSOLE_WIDTH=800 -DSPL_CONSOLE_HEIGHT=500 -DSPL_CONSOLE_ECHO -DSPL_CONSOLE_EXIT_ON_CLOSE -DSPL_VERIFY_JAVA_BACKEND_VERSION -DSPL_VERIFY_PROJECT_VERSION -DPQUEUE_ALLOW_HEAP_ACCESS -DPQUEUE_PRINT_IN_HEAP_ORDER -DSPL_THROW_ON_INVALID_ITERATOR -DSPL_CONSOLE_PRINT_EXCEPTIONS -DQT_QML_DEBUG
CFLAGS = -pipe -g -Wall -W -fPIC $(DEFINES)
CXXFLAGS = -pipe -Wall -Wextra -Wcast-align -Wfloat-equal -Wformat=2 -Wlogical-op -Wlong-long -Wno-missing-field-initializers -Wno-sign-compare -Wno-sign-conversion -Wno-write-strings -Wreturn-type -Werror=return-type -Werror=uninitialized -Wunreachable-code -Wuseless-cast -Wzero-as-null-pointer-constant -Werror=zero-as-null-pointer-constant -Wno-unused-const-variable -g3 -fno-inline -fno-omit-frame-pointer -g -std=gnu++11 -Wall -W -fPIC $(DEFINES)
INCPATH = -I../GrammarSolver/lib/StanfordCPPLib -I../GrammarSolver/lib/StanfordCPPLib/collections -I../GrammarSolver/lib/StanfordCPPLib/graphics -I../GrammarSolver/lib/StanfordCPPLib/io -I../GrammarSolver/lib/StanfordCPPLib/system -I../GrammarSolver/lib/StanfordCPPLib/util -I../GrammarSolver/src -I../GrammarSolver -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++
QMAKE = /usr/lib/qt5/bin/qmake
DEL_FILE = rm -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p
COPY = cp -f
COPY_FILE = cp -f
COPY_DIR = cp -f -R
INSTALL_FILE = install -m 644 -p
INSTALL_PROGRAM = install -m 755 -p
INSTALL_DIR = cp -f -R
QINSTALL = /usr/lib/qt5/bin/qmake -install qinstall
QINSTALL_PROGRAM = /usr/lib/qt5/bin/qmake -install qinstall -exe
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
TAR = tar -cf
COMPRESS = gzip -9f
DISTNAME = GrammarSolver1.0.0
DISTDIR = /tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug/.tmp/GrammarSolver1.0.0
LINK = g++
LFLAGS = -rdynamic -Wl,--export-dynamic
LIBS = $(SUBLIBS) -ldl -lpthread
AR = ar cqs
RANLIB =
SED = sed
STRIP = strip
####### Output directory
OBJECTS_DIR = ./
####### Files
SOURCES = ../GrammarSolver/lib/StanfordCPPLib/collections/basicgraph.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/lexicon.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/shuffle.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gfilechooser.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/goptionpane.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtextarea.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/base64.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/bitstream.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/console.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/plainconsole.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/server.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/simpio.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/urlstream.cpp \
../GrammarSolver/lib/StanfordCPPLib/private/platform.cpp \
../GrammarSolver/lib/StanfordCPPLib/private/tplatform_posix.cpp \
../GrammarSolver/lib/StanfordCPPLib/private/version.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/call_stack_gcc.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/call_stack_windows.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/error.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/process.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/thread.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/bigfloat.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/biginteger.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/complex.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/direction.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/note.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/observable.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/point.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/random.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/recursion.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/regexpr.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/sound.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/timer.cpp \
../GrammarSolver/src/grammarmain.cpp \
../GrammarSolver/src/grammarsolver.cpp
OBJECTS = basicgraph.o \
dawglexicon.o \
hashcode.o \
lexicon.o \
shuffle.o \
gbufferedimage.o \
gevents.o \
gfilechooser.o \
ginteractors.o \
gobjects.o \
goptionpane.o \
gtable.o \
gtextarea.o \
gtimer.o \
gtypes.o \
gwindow.o \
base64.o \
bitstream.o \
console.o \
filelib.o \
plainconsole.o \
server.o \
simpio.o \
tokenscanner.o \
urlstream.o \
platform.o \
tplatform_posix.o \
version.o \
call_stack_gcc.o \
call_stack_windows.o \
error.o \
exceptions.o \
process.o \
thread.o \
bigfloat.o \
biginteger.o \
complex.o \
direction.o \
gmath.o \
note.o \
observable.o \
point.o \
random.o \
recursion.o \
regexpr.o \
sound.o \
strlib.o \
timer.o \
grammarmain.o \
grammarsolver.o
DIST = /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \
../GrammarSolver/GrammarSolver.pro /tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/basicgraph.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/deque.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/graph.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/hashmap.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/hashset.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/lexicon.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/linkedhashmap.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/linkedhashset.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/linkedlist.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/map.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/pqueue.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/priorityqueue.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/queue.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/set.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/shuffle.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/sparsegrid.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/stl.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gfilechooser.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/goptionpane.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gtextarea.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/base64.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/bitstream.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/console.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/plainconsole.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/server.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/simpio.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/io/urlstream.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/consolestreambuf.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/echoinputstreambuf.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/foreachpatch.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/forwardingstreambuf.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/init.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/limitoutputstreambuf.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/platform.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/randompatch.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/static.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/tokenpatch.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/tplatform.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/private/version.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/call_stack.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/error.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/process.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/pstream.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/stack_exception.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/system/thread.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/bigfloat.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/biginteger.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/complex.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/direction.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/foreach.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/note.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/observable.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/point.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/random.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/recursion.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/regexpr.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/sound.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/StanfordCPPLib/util/timer.h \
/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/src/grammarsolver.h ../GrammarSolver/lib/StanfordCPPLib/collections/basicgraph.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/lexicon.cpp \
../GrammarSolver/lib/StanfordCPPLib/collections/shuffle.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gfilechooser.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/goptionpane.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtextarea.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.cpp \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/base64.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/bitstream.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/console.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/plainconsole.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/server.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/simpio.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.cpp \
../GrammarSolver/lib/StanfordCPPLib/io/urlstream.cpp \
../GrammarSolver/lib/StanfordCPPLib/private/platform.cpp \
../GrammarSolver/lib/StanfordCPPLib/private/tplatform_posix.cpp \
../GrammarSolver/lib/StanfordCPPLib/private/version.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/call_stack_gcc.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/call_stack_windows.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/error.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/process.cpp \
../GrammarSolver/lib/StanfordCPPLib/system/thread.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/bigfloat.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/biginteger.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/complex.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/direction.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/note.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/observable.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/point.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/random.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/recursion.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/regexpr.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/sound.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.cpp \
../GrammarSolver/lib/StanfordCPPLib/util/timer.cpp \
../GrammarSolver/src/grammarmain.cpp \
../GrammarSolver/src/grammarsolver.cpp
QMAKE_TARGET = GrammarSolver
DESTDIR =
TARGET = GrammarSolver
first: all
####### Build rules
$(TARGET): $(OBJECTS) copyResources
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)
Makefile: ../GrammarSolver/GrammarSolver.pro .qmake.cache /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \
../GrammarSolver/GrammarSolver.pro
$(QMAKE) -o Makefile ../GrammarSolver/GrammarSolver.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf:
../GrammarSolver/GrammarSolver.pro:
qmake: FORCE
@$(QMAKE) -o Makefile ../GrammarSolver/GrammarSolver.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
qmake_all: FORCE
all: Makefile $(TARGET)
dist: distdir FORCE
(cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR)
distdir: FORCE
@test -d $(DISTDIR) || mkdir -p $(DISTDIR)
$(COPY_FILE) --parents $(DIST) $(DISTDIR)/
clean: compiler_clean
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) *~ core *.core
distclean: clean
-$(DEL_FILE) $(TARGET)
-$(DEL_FILE) .qmake.stash
-$(DEL_FILE) Makefile
####### Sub-libraries
copyResources:
cp -rf "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/res/expression.txt" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
cp -rf "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/res/mygrammar.txt" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
cp -rf "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/res/nonsense.txt" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
cp -rf "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/res/sentence.txt" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
cp -rf "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/res/sentence2.txt" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
cp -rf "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/lib/spl.jar" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
first: $(first) copydata
copydata:
$(COPY_DIR) "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/GrammarSolver/output" "/tmp/guest-pveaaa/Desktop/CS106B-Stanford/Assignment-Code/Assignment03/build-GrammarSolver-Desktop-Debug"
check: first
benchmark: first
compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean:
####### Compile
basicgraph.o: ../GrammarSolver/lib/StanfordCPPLib/collections/basicgraph.cpp ../GrammarSolver/lib/StanfordCPPLib/collections/basicgraph.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/collections/graph.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/set.h \
../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.h \
../GrammarSolver/lib/StanfordCPPLib/private/tokenpatch.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/util/observable.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o basicgraph.o ../GrammarSolver/lib/StanfordCPPLib/collections/basicgraph.cpp
dawglexicon.o: ../GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.cpp ../GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.h \
../GrammarSolver/lib/StanfordCPPLib/collections/set.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o dawglexicon.o ../GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.cpp
hashcode.o: ../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.cpp ../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o hashcode.o ../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.cpp
lexicon.o: ../GrammarSolver/lib/StanfordCPPLib/collections/lexicon.cpp ../GrammarSolver/lib/StanfordCPPLib/collections/lexicon.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/collections/set.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/dawglexicon.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o lexicon.o ../GrammarSolver/lib/StanfordCPPLib/collections/lexicon.cpp
shuffle.o: ../GrammarSolver/lib/StanfordCPPLib/collections/shuffle.cpp ../GrammarSolver/lib/StanfordCPPLib/collections/shuffle.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o shuffle.o ../GrammarSolver/lib/StanfordCPPLib/collections/shuffle.cpp
gbufferedimage.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/io/base64.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gbufferedimage.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.cpp
gevents.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gevents.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.cpp
gfilechooser.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gfilechooser.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gfilechooser.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gfilechooser.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gfilechooser.cpp
ginteractors.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o ginteractors.o ../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.cpp
gobjects.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gobjects.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.cpp
goptionpane.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/goptionpane.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/goptionpane.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o goptionpane.o ../GrammarSolver/lib/StanfordCPPLib/graphics/goptionpane.cpp
gtable.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtable.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.cpp
gtextarea.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gtextarea.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gtextarea.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/io/base64.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtextarea.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gtextarea.cpp
gtimer.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtimer.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.cpp
gtypes.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtypes.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.cpp
gwindow.o: ../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.cpp ../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gwindow.o ../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.cpp
base64.o: ../GrammarSolver/lib/StanfordCPPLib/io/base64.cpp ../GrammarSolver/lib/StanfordCPPLib/io/base64.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o base64.o ../GrammarSolver/lib/StanfordCPPLib/io/base64.cpp
bitstream.o: ../GrammarSolver/lib/StanfordCPPLib/io/bitstream.cpp ../GrammarSolver/lib/StanfordCPPLib/io/bitstream.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o bitstream.o ../GrammarSolver/lib/StanfordCPPLib/io/bitstream.cpp
console.o: ../GrammarSolver/lib/StanfordCPPLib/io/console.cpp ../GrammarSolver/lib/StanfordCPPLib/io/console.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o console.o ../GrammarSolver/lib/StanfordCPPLib/io/console.cpp
filelib.o: ../GrammarSolver/lib/StanfordCPPLib/io/filelib.cpp ../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/io/simpio.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o filelib.o ../GrammarSolver/lib/StanfordCPPLib/io/filelib.cpp
plainconsole.o: ../GrammarSolver/lib/StanfordCPPLib/io/plainconsole.cpp ../GrammarSolver/lib/StanfordCPPLib/io/plainconsole.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o plainconsole.o ../GrammarSolver/lib/StanfordCPPLib/io/plainconsole.cpp
server.o: ../GrammarSolver/lib/StanfordCPPLib/io/server.cpp ../GrammarSolver/lib/StanfordCPPLib/io/server.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o server.o ../GrammarSolver/lib/StanfordCPPLib/io/server.cpp
simpio.o: ../GrammarSolver/lib/StanfordCPPLib/io/simpio.cpp ../GrammarSolver/lib/StanfordCPPLib/io/simpio.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o simpio.o ../GrammarSolver/lib/StanfordCPPLib/io/simpio.cpp
tokenscanner.o: ../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.cpp ../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.h \
../GrammarSolver/lib/StanfordCPPLib/private/tokenpatch.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o tokenscanner.o ../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.cpp
urlstream.o: ../GrammarSolver/lib/StanfordCPPLib/io/urlstream.cpp ../GrammarSolver/lib/StanfordCPPLib/io/urlstream.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o urlstream.o ../GrammarSolver/lib/StanfordCPPLib/io/urlstream.cpp
platform.o: ../GrammarSolver/lib/StanfordCPPLib/private/platform.cpp ../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/consolestreambuf.h \
../GrammarSolver/lib/StanfordCPPLib/private/forwardingstreambuf.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h \
../GrammarSolver/lib/StanfordCPPLib/private/version.h \
../GrammarSolver/lib/StanfordCPPLib/io/base64.h \
../GrammarSolver/lib/StanfordCPPLib/io/console.h \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashmap.h \
../GrammarSolver/lib/StanfordCPPLib/collections/queue.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.h \
../GrammarSolver/lib/StanfordCPPLib/private/tokenpatch.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o platform.o ../GrammarSolver/lib/StanfordCPPLib/private/platform.cpp
tplatform_posix.o: ../GrammarSolver/lib/StanfordCPPLib/private/tplatform_posix.cpp ../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/collections/map.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/stack.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/private/tplatform.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o tplatform_posix.o ../GrammarSolver/lib/StanfordCPPLib/private/tplatform_posix.cpp
version.o: ../GrammarSolver/lib/StanfordCPPLib/private/version.cpp ../GrammarSolver/lib/StanfordCPPLib/private/version.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o version.o ../GrammarSolver/lib/StanfordCPPLib/private/version.cpp
call_stack_gcc.o: ../GrammarSolver/lib/StanfordCPPLib/system/call_stack_gcc.cpp ../GrammarSolver/lib/StanfordCPPLib/system/call_stack.h \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o call_stack_gcc.o ../GrammarSolver/lib/StanfordCPPLib/system/call_stack_gcc.cpp
call_stack_windows.o: ../GrammarSolver/lib/StanfordCPPLib/system/call_stack_windows.cpp ../GrammarSolver/lib/StanfordCPPLib/system/call_stack.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o call_stack_windows.o ../GrammarSolver/lib/StanfordCPPLib/system/call_stack_windows.cpp
error.o: ../GrammarSolver/lib/StanfordCPPLib/system/error.cpp ../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o error.o ../GrammarSolver/lib/StanfordCPPLib/system/error.cpp
exceptions.o: ../GrammarSolver/lib/StanfordCPPLib/system/exceptions.cpp ../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/call_stack.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o exceptions.o ../GrammarSolver/lib/StanfordCPPLib/system/exceptions.cpp
process.o: ../GrammarSolver/lib/StanfordCPPLib/system/process.cpp ../GrammarSolver/lib/StanfordCPPLib/system/process.h \
../GrammarSolver/lib/StanfordCPPLib/system/pstream.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o process.o ../GrammarSolver/lib/StanfordCPPLib/system/process.cpp
thread.o: ../GrammarSolver/lib/StanfordCPPLib/system/thread.cpp ../GrammarSolver/lib/StanfordCPPLib/system/thread.h \
../GrammarSolver/lib/StanfordCPPLib/private/tplatform.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o thread.o ../GrammarSolver/lib/StanfordCPPLib/system/thread.cpp
bigfloat.o: ../GrammarSolver/lib/StanfordCPPLib/util/bigfloat.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o bigfloat.o ../GrammarSolver/lib/StanfordCPPLib/util/bigfloat.cpp
biginteger.o: ../GrammarSolver/lib/StanfordCPPLib/util/biginteger.cpp ../GrammarSolver/lib/StanfordCPPLib/util/biginteger.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o biginteger.o ../GrammarSolver/lib/StanfordCPPLib/util/biginteger.cpp
complex.o: ../GrammarSolver/lib/StanfordCPPLib/util/complex.cpp ../GrammarSolver/lib/StanfordCPPLib/util/complex.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o complex.o ../GrammarSolver/lib/StanfordCPPLib/util/complex.cpp
direction.o: ../GrammarSolver/lib/StanfordCPPLib/util/direction.cpp ../GrammarSolver/lib/StanfordCPPLib/util/direction.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/io/tokenscanner.h \
../GrammarSolver/lib/StanfordCPPLib/private/tokenpatch.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o direction.o ../GrammarSolver/lib/StanfordCPPLib/util/direction.cpp
gmath.o: ../GrammarSolver/lib/StanfordCPPLib/util/gmath.cpp ../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gmath.o ../GrammarSolver/lib/StanfordCPPLib/util/gmath.cpp
note.o: ../GrammarSolver/lib/StanfordCPPLib/util/note.cpp ../GrammarSolver/lib/StanfordCPPLib/util/note.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o note.o ../GrammarSolver/lib/StanfordCPPLib/util/note.cpp
observable.o: ../GrammarSolver/lib/StanfordCPPLib/util/observable.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o observable.o ../GrammarSolver/lib/StanfordCPPLib/util/observable.cpp
point.o: ../GrammarSolver/lib/StanfordCPPLib/util/point.cpp ../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o point.o ../GrammarSolver/lib/StanfordCPPLib/util/point.cpp
random.o: ../GrammarSolver/lib/StanfordCPPLib/util/random.cpp ../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o random.o ../GrammarSolver/lib/StanfordCPPLib/util/random.cpp
recursion.o: ../GrammarSolver/lib/StanfordCPPLib/util/recursion.cpp ../GrammarSolver/lib/StanfordCPPLib/util/recursion.h \
../GrammarSolver/lib/StanfordCPPLib/system/exceptions.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/call_stack.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o recursion.o ../GrammarSolver/lib/StanfordCPPLib/util/recursion.cpp
regexpr.o: ../GrammarSolver/lib/StanfordCPPLib/util/regexpr.cpp ../GrammarSolver/lib/StanfordCPPLib/util/regexpr.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h \
../GrammarSolver/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o regexpr.o ../GrammarSolver/lib/StanfordCPPLib/util/regexpr.cpp
sound.o: ../GrammarSolver/lib/StanfordCPPLib/util/sound.cpp ../GrammarSolver/lib/StanfordCPPLib/util/sound.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/private/platform.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gevents.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtable.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtimer.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o sound.o ../GrammarSolver/lib/StanfordCPPLib/util/sound.cpp
strlib.o: ../GrammarSolver/lib/StanfordCPPLib/util/strlib.cpp ../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o strlib.o ../GrammarSolver/lib/StanfordCPPLib/util/strlib.cpp
timer.o: ../GrammarSolver/lib/StanfordCPPLib/util/timer.cpp ../GrammarSolver/lib/StanfordCPPLib/util/timer.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o timer.o ../GrammarSolver/lib/StanfordCPPLib/util/timer.cpp
grammarmain.o: ../GrammarSolver/src/grammarmain.cpp ../GrammarSolver/lib/StanfordCPPLib/io/console.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/io/filelib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/io/simpio.h \
../GrammarSolver/src/grammarsolver.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o grammarmain.o ../GrammarSolver/src/grammarmain.cpp
grammarsolver.o: ../GrammarSolver/src/grammarsolver.cpp ../GrammarSolver/src/grammarsolver.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../GrammarSolver/lib/StanfordCPPLib/collections/grid.h \
../GrammarSolver/lib/StanfordCPPLib/collections/collections.h \
../GrammarSolver/lib/StanfordCPPLib/system/error.h \
../GrammarSolver/lib/StanfordCPPLib/private/init.h \
../GrammarSolver/lib/StanfordCPPLib/util/gmath.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gtypes.h \
../GrammarSolver/lib/StanfordCPPLib/collections/hashcode.h \
../GrammarSolver/lib/StanfordCPPLib/util/random.h \
../GrammarSolver/lib/StanfordCPPLib/util/strlib.h \
../GrammarSolver/lib/StanfordCPPLib/collections/vector.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/ginteractors.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gobjects.h \
../GrammarSolver/lib/StanfordCPPLib/graphics/gwindow.h \
../GrammarSolver/lib/StanfordCPPLib/util/point.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o grammarsolver.o ../GrammarSolver/src/grammarsolver.cpp
####### Install
install: FORCE
uninstall: FORCE
FORCE:
<file_sep>#include "DoubleScriptedArray.h"
#include <stdexcept>
#include <iostream>
#include <iomanip>
using namespace std;
ostream& operator<<(ostream& output, const DoubleScriptedArray& a){
for(int i=0;i<a.row;i++){
for(int j=0;j<a.col;j++){
output << a(i, j) << " ";
}
output << endl;
}
return output;
}
istream& operator>>(istream& input, DoubleScriptedArray& a){
for(int i=0;i<a.row;i++){
for(int j=0;j<a.col;j++){
input >> a(i, j);
}
}
return input;
}
DoubleScriptedArray::DoubleScriptedArray(int m, int n)
: row{m}, col{n}, ptr{new int[m*n]}{
/* empty body */
}
DoubleScriptedArray::DoubleScriptedArray(const DoubleScriptedArray& toCopy)
: row{toCopy.getRowSize()}, col{toCopy.getColSize()}, ptr{new int[row*col]}{
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
(*this)(i, j) = toCopy(i, j);
}
}
}
DoubleScriptedArray::~DoubleScriptedArray(){
delete[] ptr;
}
int DoubleScriptedArray::getRowSize() const{
return row;
}
int DoubleScriptedArray::getColSize() const{
return col;
}
const DoubleScriptedArray& DoubleScriptedArray::operator=(const DoubleScriptedArray& right){
// self assignment?
if(&right != this){
if(col != right.col || row != right.row){
delete[] ptr;
col = right.col;
row = right.row;
ptr = new int[row*col];
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
(*this)(i, j) = right(i, j);
}
}
}
}
bool DoubleScriptedArray::operator==(const DoubleScriptedArray& right) const{
if(col != right.col || row != right.row){
return false;
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if((*this)(i, j) != right(i, j)){
return false;
}
}
}
return true;
}
int DoubleScriptedArray::operator()(int i, int j) const{
if(i<row && j<col){
return ptr[row * i + j];
} else{
throw out_of_range{"Array out of bounds!"};
}
}
int& DoubleScriptedArray::operator()(int i, int j){
if(i<row && j<col){
return ptr[row * i + j];
} else{
throw out_of_range{"Array out of bounds!"};
}
}<file_sep>// heappatientqueue.cpp
// This is the CPP file you will edit and turn in. (TODO: Remove this comment!)
#include "HeapPatientQueue.h"
#include "strlib.h"
#include <sstream>
#include <iostream>
HeapPatientQueue::HeapPatientQueue() {
pq = new Patient[capacity];
size = 0;
}
HeapPatientQueue::~HeapPatientQueue() {
delete[] pq;
}
// private member function to resize pq
void HeapPatientQueue::resize(){
int tempCap = capacity * 2;
Patient *pqTemp;
pqTemp = new Patient[tempCap];
for(int i=1;i<capacity;i++){
pqTemp[i] = pq[i];
}
pq = pqTemp;
capacity = tempCap;
}
// returns 1 if p1 comes first (higher priority) and -1 if not the case.
int HeapPatientQueue::comparePatient(Patient p1, Patient p2){
if(p1.priority < p2.priority){
return 1;
} else if(p1.priority == p2.priority){
if(p1.name < p2.name){
return 1;
} else{
return -1;
}
} else{
return -1;
}
}
void HeapPatientQueue::clear() {
delete[] pq;
pq = new Patient[capacity];
size = 0;
}
string HeapPatientQueue::frontName() {
if(isEmpty()){
throw "Patient Queue is Empty";
} else{
return pq[1].name;
}
}
int HeapPatientQueue::frontPriority() {
if(isEmpty()){
throw "Patient Queue is Empty";
} else{
return pq[1].priority;
}
}
bool HeapPatientQueue::isEmpty() {
return (size == 0);
}
void HeapPatientQueue::newPatient(string name, int priority) {
// Instantiate new patient struct
Patient newPatient(name, priority);
// check if the pq is full or not
if(size == capacity-1){
resize();
}
// Now percolate the patient up....
int index = size + 1;
pq[index] = newPatient;
size++;
while(index > 1){
if(comparePatient(pq[index], pq[index/2]) > 0){
// tempPatient needs to come first: swap.
Patient tempPatient = pq[index];
pq[index] = pq[index/2];
pq[index/2] = tempPatient;
// assign current value of index
index = index/2;
} else{
break;
}
}
}
string HeapPatientQueue::processPatient() {
string tempName = frontName();
pq[1] = pq[size];
size--; // decrement size after deletion.
// now percolate pq[1] down.
int index = 1;
int swapIndex;
while(index <= size/2){
if(comparePatient(pq[index*2], pq[index]) > 0){
swapIndex = index*2;
} else if(index*2 + 1 <= size && comparePatient(pq[index*2+1], pq[index]) > 0){
swapIndex = index*2+1;
} else{
// in the right place
break;
}
// swap with index
Patient temp = pq[swapIndex];
pq[swapIndex] = pq[index];
pq[index] = temp;
index = index*2;
}
return tempName; // this is only here so it will compile
}
void HeapPatientQueue::upgradePatient(string name, int newPriority) {
int tempPriority = INT_FAST8_MAX;
int indexPatient = -1;
for(int i=1;i<size+1;i++){
if(pq[i].name == name){
if(pq[i].priority < tempPriority){
indexPatient = i;
}
}
}
if(indexPatient == -1){
throw "Patient not on queue";
}
if(newPriority >= pq[indexPatient].priority){
throw "Patient already has higher priority";
}
// update the priority
pq[indexPatient].priority = newPriority;
// now we need to percolate this patient up if needed.
int index = indexPatient;
while(index > 1){
if(comparePatient(pq[index], pq[index/2]) > 0){
// tempPatient needs to come first: swap.
Patient tempPatient = pq[index];
pq[index] = pq[index/2];
pq[index/2] = tempPatient;
// assign current value of index
index = index/2;
} else{
break;
}
}
}
string HeapPatientQueue::toString() {
stringstream s;
s << "{";
for(int i=1;i<size+1;i++){
s << pq[i].priority << ":" << pq[i].name;
if(i != size){
s << ", ";
}
}
s << "}";
return s.str();
return s.str();
}
<file_sep>#ifndef ARRAYSTACK_H
#define ARRAYSTACK_H
#include <iostream>
using namespace std;
class ArrayStack{
public:
ArrayStack();
~ArrayStack(); // destructor
void push(int n);
int peek() const;
bool isEmpty() const;
string toString() const;
private:
int* elements;
int size;
int capacity;
};
// making objects printable
ostream& operator <<(ostream& out, ArrayStack& stack);
#endif // ARRAYSTACK_H
<file_sep>#############################################################################
# Makefile for building: PatientQueue
# Generated by qmake (3.1) (Qt 5.9.5)
# Project: ../PatientQueue/PatientQueue.pro
# Template: app
# Command: /usr/lib/qt5/bin/qmake -o Makefile ../PatientQueue/PatientQueue.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
#############################################################################
MAKEFILE = Makefile
####### Compiler, tools and options
CC = gcc
CXX = g++
DEFINES = -DSPL_PROJECT_VERSION=20171115 -DSPL_CONSOLE_X=-1 -DSPL_CONSOLE_Y=-1 -DSPL_CONSOLE_WIDTH=800 -DSPL_CONSOLE_HEIGHT=500 -DSPL_CONSOLE_ECHO -DSPL_CONSOLE_EXIT_ON_CLOSE -DSPL_VERIFY_JAVA_BACKEND_VERSION -DSPL_VERIFY_PROJECT_VERSION -DPQUEUE_ALLOW_HEAP_ACCESS -DPQUEUE_PRINT_IN_HEAP_ORDER -DSPL_THROW_ON_INVALID_ITERATOR -DSPL_CONSOLE_PRINT_EXCEPTIONS -DQT_QML_DEBUG
CFLAGS = -pipe -g -Wall -W -fPIC $(DEFINES)
CXXFLAGS = -pipe -Wall -Wextra -Wcast-align -Wfloat-equal -Wformat=2 -Wlogical-op -Wlong-long -Wno-missing-field-initializers -Wno-sign-compare -Wno-sign-conversion -Wno-write-strings -Wreturn-type -Werror=return-type -Werror=uninitialized -Wunreachable-code -Wuseless-cast -Wno-unused-const-variable -g3 -fno-inline -fno-omit-frame-pointer -g -std=gnu++11 -Wall -W -fPIC $(DEFINES)
INCPATH = -I../PatientQueue/lib/StanfordCPPLib -I../PatientQueue/lib/StanfordCPPLib/collections -I../PatientQueue/lib/StanfordCPPLib/graphics -I../PatientQueue/lib/StanfordCPPLib/io -I../PatientQueue/lib/StanfordCPPLib/system -I../PatientQueue/lib/StanfordCPPLib/util -I../PatientQueue/src -I../PatientQueue -I/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++
QMAKE = /usr/lib/qt5/bin/qmake
DEL_FILE = rm -f
CHK_DIR_EXISTS= test -d
MKDIR = mkdir -p
COPY = cp -f
COPY_FILE = cp -f
COPY_DIR = cp -f -R
INSTALL_FILE = install -m 644 -p
INSTALL_PROGRAM = install -m 755 -p
INSTALL_DIR = cp -f -R
QINSTALL = /usr/lib/qt5/bin/qmake -install qinstall
QINSTALL_PROGRAM = /usr/lib/qt5/bin/qmake -install qinstall -exe
DEL_FILE = rm -f
SYMLINK = ln -f -s
DEL_DIR = rmdir
MOVE = mv -f
TAR = tar -cf
COMPRESS = gzip -9f
DISTNAME = PatientQueue1.0.0
DISTDIR = /tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/build-PatientQueue-Desktop-Debug/.tmp/PatientQueue1.0.0
LINK = g++
LFLAGS = -rdynamic -Wl,--export-dynamic
LIBS = $(SUBLIBS) -ldl -lpthread
AR = ar cqs
RANLIB =
SED = sed
STRIP = strip
####### Output directory
OBJECTS_DIR = ./
####### Files
SOURCES = ../PatientQueue/lib/StanfordCPPLib/collections/basicgraph.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/lexicon.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/shuffle.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gfilechooser.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/goptionpane.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtextarea.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.cpp \
../PatientQueue/lib/StanfordCPPLib/io/base64.cpp \
../PatientQueue/lib/StanfordCPPLib/io/bitstream.cpp \
../PatientQueue/lib/StanfordCPPLib/io/console.cpp \
../PatientQueue/lib/StanfordCPPLib/io/filelib.cpp \
../PatientQueue/lib/StanfordCPPLib/io/plainconsole.cpp \
../PatientQueue/lib/StanfordCPPLib/io/server.cpp \
../PatientQueue/lib/StanfordCPPLib/io/simpio.cpp \
../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.cpp \
../PatientQueue/lib/StanfordCPPLib/io/urlstream.cpp \
../PatientQueue/lib/StanfordCPPLib/private/platform.cpp \
../PatientQueue/lib/StanfordCPPLib/private/tplatform_posix.cpp \
../PatientQueue/lib/StanfordCPPLib/private/version.cpp \
../PatientQueue/lib/StanfordCPPLib/system/call_stack_gcc.cpp \
../PatientQueue/lib/StanfordCPPLib/system/call_stack_windows.cpp \
../PatientQueue/lib/StanfordCPPLib/system/error.cpp \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.cpp \
../PatientQueue/lib/StanfordCPPLib/system/process.cpp \
../PatientQueue/lib/StanfordCPPLib/system/thread.cpp \
../PatientQueue/lib/StanfordCPPLib/util/bigfloat.cpp \
../PatientQueue/lib/StanfordCPPLib/util/biginteger.cpp \
../PatientQueue/lib/StanfordCPPLib/util/complex.cpp \
../PatientQueue/lib/StanfordCPPLib/util/direction.cpp \
../PatientQueue/lib/StanfordCPPLib/util/gmath.cpp \
../PatientQueue/lib/StanfordCPPLib/util/note.cpp \
../PatientQueue/lib/StanfordCPPLib/util/observable.cpp \
../PatientQueue/lib/StanfordCPPLib/util/point.cpp \
../PatientQueue/lib/StanfordCPPLib/util/random.cpp \
../PatientQueue/lib/StanfordCPPLib/util/recursion.cpp \
../PatientQueue/lib/StanfordCPPLib/util/regexpr.cpp \
../PatientQueue/lib/StanfordCPPLib/util/sound.cpp \
../PatientQueue/lib/StanfordCPPLib/util/strlib.cpp \
../PatientQueue/lib/StanfordCPPLib/util/timer.cpp \
../PatientQueue/src/HeapPatientQueue.cpp \
../PatientQueue/src/hospital.cpp \
../PatientQueue/src/LinkedListPatientQueue.cpp \
../PatientQueue/src/patientnode.cpp \
../PatientQueue/src/VectorPatientQueue.cpp
OBJECTS = basicgraph.o \
dawglexicon.o \
hashcode.o \
lexicon.o \
shuffle.o \
gbufferedimage.o \
gevents.o \
gfilechooser.o \
ginteractors.o \
gobjects.o \
goptionpane.o \
gtable.o \
gtextarea.o \
gtimer.o \
gtypes.o \
gwindow.o \
base64.o \
bitstream.o \
console.o \
filelib.o \
plainconsole.o \
server.o \
simpio.o \
tokenscanner.o \
urlstream.o \
platform.o \
tplatform_posix.o \
version.o \
call_stack_gcc.o \
call_stack_windows.o \
error.o \
exceptions.o \
process.o \
thread.o \
bigfloat.o \
biginteger.o \
complex.o \
direction.o \
gmath.o \
note.o \
observable.o \
point.o \
random.o \
recursion.o \
regexpr.o \
sound.o \
strlib.o \
timer.o \
HeapPatientQueue.o \
hospital.o \
LinkedListPatientQueue.o \
patientnode.o \
VectorPatientQueue.o
DIST = /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \
../PatientQueue/PatientQueue.pro /tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/basicgraph.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/collections.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/deque.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/graph.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/grid.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/hashmap.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/hashset.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/lexicon.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/linkedhashmap.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/linkedhashset.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/linkedlist.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/map.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/pqueue.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/priorityqueue.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/queue.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/set.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/shuffle.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/sparsegrid.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/stack.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/stl.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/collections/vector.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gfilechooser.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/goptionpane.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gtextarea.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/base64.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/bitstream.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/console.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/filelib.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/plainconsole.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/server.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/simpio.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/tokenscanner.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/io/urlstream.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/consolestreambuf.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/echoinputstreambuf.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/foreachpatch.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/forwardingstreambuf.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/init.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/limitoutputstreambuf.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/platform.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/randompatch.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/static.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/tokenpatch.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/tplatform.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/private/version.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/call_stack.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/error.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/process.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/pstream.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/stack_exception.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/system/thread.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/bigfloat.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/biginteger.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/complex.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/direction.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/foreach.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/gmath.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/note.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/observable.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/point.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/random.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/recursion.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/regexpr.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/sound.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/strlib.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/StanfordCPPLib/util/timer.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/src/HeapPatientQueue.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/src/LinkedListPatientQueue.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/src/patientnode.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/src/patientqueue.h \
/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/src/VectorPatientQueue.h ../PatientQueue/lib/StanfordCPPLib/collections/basicgraph.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/lexicon.cpp \
../PatientQueue/lib/StanfordCPPLib/collections/shuffle.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gfilechooser.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/goptionpane.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtextarea.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.cpp \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.cpp \
../PatientQueue/lib/StanfordCPPLib/io/base64.cpp \
../PatientQueue/lib/StanfordCPPLib/io/bitstream.cpp \
../PatientQueue/lib/StanfordCPPLib/io/console.cpp \
../PatientQueue/lib/StanfordCPPLib/io/filelib.cpp \
../PatientQueue/lib/StanfordCPPLib/io/plainconsole.cpp \
../PatientQueue/lib/StanfordCPPLib/io/server.cpp \
../PatientQueue/lib/StanfordCPPLib/io/simpio.cpp \
../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.cpp \
../PatientQueue/lib/StanfordCPPLib/io/urlstream.cpp \
../PatientQueue/lib/StanfordCPPLib/private/platform.cpp \
../PatientQueue/lib/StanfordCPPLib/private/tplatform_posix.cpp \
../PatientQueue/lib/StanfordCPPLib/private/version.cpp \
../PatientQueue/lib/StanfordCPPLib/system/call_stack_gcc.cpp \
../PatientQueue/lib/StanfordCPPLib/system/call_stack_windows.cpp \
../PatientQueue/lib/StanfordCPPLib/system/error.cpp \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.cpp \
../PatientQueue/lib/StanfordCPPLib/system/process.cpp \
../PatientQueue/lib/StanfordCPPLib/system/thread.cpp \
../PatientQueue/lib/StanfordCPPLib/util/bigfloat.cpp \
../PatientQueue/lib/StanfordCPPLib/util/biginteger.cpp \
../PatientQueue/lib/StanfordCPPLib/util/complex.cpp \
../PatientQueue/lib/StanfordCPPLib/util/direction.cpp \
../PatientQueue/lib/StanfordCPPLib/util/gmath.cpp \
../PatientQueue/lib/StanfordCPPLib/util/note.cpp \
../PatientQueue/lib/StanfordCPPLib/util/observable.cpp \
../PatientQueue/lib/StanfordCPPLib/util/point.cpp \
../PatientQueue/lib/StanfordCPPLib/util/random.cpp \
../PatientQueue/lib/StanfordCPPLib/util/recursion.cpp \
../PatientQueue/lib/StanfordCPPLib/util/regexpr.cpp \
../PatientQueue/lib/StanfordCPPLib/util/sound.cpp \
../PatientQueue/lib/StanfordCPPLib/util/strlib.cpp \
../PatientQueue/lib/StanfordCPPLib/util/timer.cpp \
../PatientQueue/src/HeapPatientQueue.cpp \
../PatientQueue/src/hospital.cpp \
../PatientQueue/src/LinkedListPatientQueue.cpp \
../PatientQueue/src/patientnode.cpp \
../PatientQueue/src/VectorPatientQueue.cpp
QMAKE_TARGET = PatientQueue
DESTDIR =
TARGET = PatientQueue
first: all
####### Build rules
$(TARGET): $(OBJECTS) copyResources
$(LINK) $(LFLAGS) -o $(TARGET) $(OBJECTS) $(OBJCOMP) $(LIBS)
Makefile: ../PatientQueue/PatientQueue.pro .qmake.cache /usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf /usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf \
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf \
../PatientQueue/PatientQueue.pro
$(QMAKE) -o Makefile ../PatientQueue/PatientQueue.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_pre.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/linux.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/sanitize.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/gcc-base-unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-base.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/common/g++-unix.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/qconfig.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_accessibility_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_bootstrap_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_concurrent_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_core_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_dbus_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_devicediscovery_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_egl_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfs_kms_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eglfsdeviceintegration_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_eventdispatcher_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fb_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_fontdatabase_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_glx_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_gui_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_input_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_kms_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_linuxaccessibility_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_network_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_opengl_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_openglextensions_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_platformcompositor_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_printsupport_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_service_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_sql_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_testlib_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_theme_support_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_widgets_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xcb_qpa_lib_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/modules/qt_lib_xml_private.pri:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_functions.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qt_config.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++/qmake.conf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/spec_post.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exclusive_builds.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/toolchain.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_pre.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/resolve_config.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/default_post.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qml_debug.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/warn_on.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/qmake_use.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/file_copies.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/testcase_targets.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/exceptions.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/yacc.prf:
/usr/lib/x86_64-linux-gnu/qt5/mkspecs/features/lex.prf:
../PatientQueue/PatientQueue.pro:
qmake: FORCE
@$(QMAKE) -o Makefile ../PatientQueue/PatientQueue.pro -spec linux-g++ CONFIG+=debug CONFIG+=qml_debug
qmake_all: FORCE
all: Makefile $(TARGET)
dist: distdir FORCE
(cd `dirname $(DISTDIR)` && $(TAR) $(DISTNAME).tar $(DISTNAME) && $(COMPRESS) $(DISTNAME).tar) && $(MOVE) `dirname $(DISTDIR)`/$(DISTNAME).tar.gz . && $(DEL_FILE) -r $(DISTDIR)
distdir: FORCE
@test -d $(DISTDIR) || mkdir -p $(DISTDIR)
$(COPY_FILE) --parents $(DIST) $(DISTDIR)/
clean: compiler_clean
-$(DEL_FILE) $(OBJECTS)
-$(DEL_FILE) *~ core *.core
distclean: clean
-$(DEL_FILE) $(TARGET)
-$(DEL_FILE) .qmake.stash
-$(DEL_FILE) Makefile
####### Sub-libraries
copyResources:
cp -rf "/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/lib/spl.jar" "/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/build-PatientQueue-Desktop-Debug"
first: $(first) copydata
copydata:
$(COPY_DIR) "/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/PatientQueue/output" "/tmp/guest-3zdaoe/Desktop/CS106B-Stanford/Assignment-Code/Assignment05/build-PatientQueue-Desktop-Debug"
check: first
benchmark: first
compiler_yacc_decl_make_all:
compiler_yacc_decl_clean:
compiler_yacc_impl_make_all:
compiler_yacc_impl_clean:
compiler_lex_make_all:
compiler_lex_clean:
compiler_clean:
####### Compile
basicgraph.o: ../PatientQueue/lib/StanfordCPPLib/collections/basicgraph.cpp ../PatientQueue/lib/StanfordCPPLib/collections/basicgraph.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/collections/graph.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/set.h \
../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.h \
../PatientQueue/lib/StanfordCPPLib/private/tokenpatch.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/util/observable.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o basicgraph.o ../PatientQueue/lib/StanfordCPPLib/collections/basicgraph.cpp
dawglexicon.o: ../PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.cpp ../PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.h \
../PatientQueue/lib/StanfordCPPLib/collections/set.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o dawglexicon.o ../PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.cpp
hashcode.o: ../PatientQueue/lib/StanfordCPPLib/collections/hashcode.cpp ../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o hashcode.o ../PatientQueue/lib/StanfordCPPLib/collections/hashcode.cpp
lexicon.o: ../PatientQueue/lib/StanfordCPPLib/collections/lexicon.cpp ../PatientQueue/lib/StanfordCPPLib/collections/lexicon.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/collections/set.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/dawglexicon.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o lexicon.o ../PatientQueue/lib/StanfordCPPLib/collections/lexicon.cpp
shuffle.o: ../PatientQueue/lib/StanfordCPPLib/collections/shuffle.cpp ../PatientQueue/lib/StanfordCPPLib/collections/shuffle.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o shuffle.o ../PatientQueue/lib/StanfordCPPLib/collections/shuffle.cpp
gbufferedimage.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/io/base64.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gbufferedimage.o ../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.cpp
gevents.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gevents.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gevents.o ../PatientQueue/lib/StanfordCPPLib/graphics/gevents.cpp
gfilechooser.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gfilechooser.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gfilechooser.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gfilechooser.o ../PatientQueue/lib/StanfordCPPLib/graphics/gfilechooser.cpp
ginteractors.o: ../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o ginteractors.o ../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.cpp
gobjects.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gobjects.o ../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.cpp
goptionpane.o: ../PatientQueue/lib/StanfordCPPLib/graphics/goptionpane.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/goptionpane.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o goptionpane.o ../PatientQueue/lib/StanfordCPPLib/graphics/goptionpane.cpp
gtable.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gtable.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtable.o ../PatientQueue/lib/StanfordCPPLib/graphics/gtable.cpp
gtextarea.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gtextarea.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gtextarea.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/io/base64.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtextarea.o ../PatientQueue/lib/StanfordCPPLib/graphics/gtextarea.cpp
gtimer.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtimer.o ../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.cpp
gtypes.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gtypes.o ../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.cpp
gwindow.o: ../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.cpp ../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gwindow.o ../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.cpp
base64.o: ../PatientQueue/lib/StanfordCPPLib/io/base64.cpp ../PatientQueue/lib/StanfordCPPLib/io/base64.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o base64.o ../PatientQueue/lib/StanfordCPPLib/io/base64.cpp
bitstream.o: ../PatientQueue/lib/StanfordCPPLib/io/bitstream.cpp ../PatientQueue/lib/StanfordCPPLib/io/bitstream.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o bitstream.o ../PatientQueue/lib/StanfordCPPLib/io/bitstream.cpp
console.o: ../PatientQueue/lib/StanfordCPPLib/io/console.cpp ../PatientQueue/lib/StanfordCPPLib/io/console.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o console.o ../PatientQueue/lib/StanfordCPPLib/io/console.cpp
filelib.o: ../PatientQueue/lib/StanfordCPPLib/io/filelib.cpp ../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/io/simpio.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o filelib.o ../PatientQueue/lib/StanfordCPPLib/io/filelib.cpp
plainconsole.o: ../PatientQueue/lib/StanfordCPPLib/io/plainconsole.cpp ../PatientQueue/lib/StanfordCPPLib/io/plainconsole.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o plainconsole.o ../PatientQueue/lib/StanfordCPPLib/io/plainconsole.cpp
server.o: ../PatientQueue/lib/StanfordCPPLib/io/server.cpp ../PatientQueue/lib/StanfordCPPLib/io/server.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o server.o ../PatientQueue/lib/StanfordCPPLib/io/server.cpp
simpio.o: ../PatientQueue/lib/StanfordCPPLib/io/simpio.cpp ../PatientQueue/lib/StanfordCPPLib/io/simpio.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o simpio.o ../PatientQueue/lib/StanfordCPPLib/io/simpio.cpp
tokenscanner.o: ../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.cpp ../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.h \
../PatientQueue/lib/StanfordCPPLib/private/tokenpatch.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o tokenscanner.o ../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.cpp
urlstream.o: ../PatientQueue/lib/StanfordCPPLib/io/urlstream.cpp ../PatientQueue/lib/StanfordCPPLib/io/urlstream.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o urlstream.o ../PatientQueue/lib/StanfordCPPLib/io/urlstream.cpp
platform.o: ../PatientQueue/lib/StanfordCPPLib/private/platform.cpp ../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/consolestreambuf.h \
../PatientQueue/lib/StanfordCPPLib/private/forwardingstreambuf.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h \
../PatientQueue/lib/StanfordCPPLib/private/version.h \
../PatientQueue/lib/StanfordCPPLib/io/base64.h \
../PatientQueue/lib/StanfordCPPLib/io/console.h \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gbufferedimage.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashmap.h \
../PatientQueue/lib/StanfordCPPLib/collections/queue.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.h \
../PatientQueue/lib/StanfordCPPLib/private/tokenpatch.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o platform.o ../PatientQueue/lib/StanfordCPPLib/private/platform.cpp
tplatform_posix.o: ../PatientQueue/lib/StanfordCPPLib/private/tplatform_posix.cpp ../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/collections/map.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/stack.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/private/tplatform.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o tplatform_posix.o ../PatientQueue/lib/StanfordCPPLib/private/tplatform_posix.cpp
version.o: ../PatientQueue/lib/StanfordCPPLib/private/version.cpp ../PatientQueue/lib/StanfordCPPLib/private/version.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o version.o ../PatientQueue/lib/StanfordCPPLib/private/version.cpp
call_stack_gcc.o: ../PatientQueue/lib/StanfordCPPLib/system/call_stack_gcc.cpp ../PatientQueue/lib/StanfordCPPLib/system/call_stack.h \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o call_stack_gcc.o ../PatientQueue/lib/StanfordCPPLib/system/call_stack_gcc.cpp
call_stack_windows.o: ../PatientQueue/lib/StanfordCPPLib/system/call_stack_windows.cpp ../PatientQueue/lib/StanfordCPPLib/system/call_stack.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o call_stack_windows.o ../PatientQueue/lib/StanfordCPPLib/system/call_stack_windows.cpp
error.o: ../PatientQueue/lib/StanfordCPPLib/system/error.cpp ../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o error.o ../PatientQueue/lib/StanfordCPPLib/system/error.cpp
exceptions.o: ../PatientQueue/lib/StanfordCPPLib/system/exceptions.cpp ../PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/call_stack.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/io/filelib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o exceptions.o ../PatientQueue/lib/StanfordCPPLib/system/exceptions.cpp
process.o: ../PatientQueue/lib/StanfordCPPLib/system/process.cpp ../PatientQueue/lib/StanfordCPPLib/system/process.h \
../PatientQueue/lib/StanfordCPPLib/system/pstream.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o process.o ../PatientQueue/lib/StanfordCPPLib/system/process.cpp
thread.o: ../PatientQueue/lib/StanfordCPPLib/system/thread.cpp ../PatientQueue/lib/StanfordCPPLib/system/thread.h \
../PatientQueue/lib/StanfordCPPLib/private/tplatform.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o thread.o ../PatientQueue/lib/StanfordCPPLib/system/thread.cpp
bigfloat.o: ../PatientQueue/lib/StanfordCPPLib/util/bigfloat.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o bigfloat.o ../PatientQueue/lib/StanfordCPPLib/util/bigfloat.cpp
biginteger.o: ../PatientQueue/lib/StanfordCPPLib/util/biginteger.cpp ../PatientQueue/lib/StanfordCPPLib/util/biginteger.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o biginteger.o ../PatientQueue/lib/StanfordCPPLib/util/biginteger.cpp
complex.o: ../PatientQueue/lib/StanfordCPPLib/util/complex.cpp ../PatientQueue/lib/StanfordCPPLib/util/complex.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o complex.o ../PatientQueue/lib/StanfordCPPLib/util/complex.cpp
direction.o: ../PatientQueue/lib/StanfordCPPLib/util/direction.cpp ../PatientQueue/lib/StanfordCPPLib/util/direction.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/io/tokenscanner.h \
../PatientQueue/lib/StanfordCPPLib/private/tokenpatch.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o direction.o ../PatientQueue/lib/StanfordCPPLib/util/direction.cpp
gmath.o: ../PatientQueue/lib/StanfordCPPLib/util/gmath.cpp ../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o gmath.o ../PatientQueue/lib/StanfordCPPLib/util/gmath.cpp
note.o: ../PatientQueue/lib/StanfordCPPLib/util/note.cpp ../PatientQueue/lib/StanfordCPPLib/util/note.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o note.o ../PatientQueue/lib/StanfordCPPLib/util/note.cpp
observable.o: ../PatientQueue/lib/StanfordCPPLib/util/observable.cpp
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o observable.o ../PatientQueue/lib/StanfordCPPLib/util/observable.cpp
point.o: ../PatientQueue/lib/StanfordCPPLib/util/point.cpp ../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o point.o ../PatientQueue/lib/StanfordCPPLib/util/point.cpp
random.o: ../PatientQueue/lib/StanfordCPPLib/util/random.cpp ../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/private/static.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o random.o ../PatientQueue/lib/StanfordCPPLib/util/random.cpp
recursion.o: ../PatientQueue/lib/StanfordCPPLib/util/recursion.cpp ../PatientQueue/lib/StanfordCPPLib/util/recursion.h \
../PatientQueue/lib/StanfordCPPLib/system/exceptions.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/call_stack.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o recursion.o ../PatientQueue/lib/StanfordCPPLib/util/recursion.cpp
regexpr.o: ../PatientQueue/lib/StanfordCPPLib/util/regexpr.cpp ../PatientQueue/lib/StanfordCPPLib/util/regexpr.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h \
../PatientQueue/lib/StanfordCPPLib/util/sound.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o regexpr.o ../PatientQueue/lib/StanfordCPPLib/util/regexpr.cpp
sound.o: ../PatientQueue/lib/StanfordCPPLib/util/sound.cpp ../PatientQueue/lib/StanfordCPPLib/util/sound.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/private/platform.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gevents.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtable.h \
../PatientQueue/lib/StanfordCPPLib/collections/grid.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/graphics/ginteractors.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gobjects.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gwindow.h \
../PatientQueue/lib/StanfordCPPLib/util/point.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtimer.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o sound.o ../PatientQueue/lib/StanfordCPPLib/util/sound.cpp
strlib.o: ../PatientQueue/lib/StanfordCPPLib/util/strlib.cpp ../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o strlib.o ../PatientQueue/lib/StanfordCPPLib/util/strlib.cpp
timer.o: ../PatientQueue/lib/StanfordCPPLib/util/timer.cpp ../PatientQueue/lib/StanfordCPPLib/util/timer.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o timer.o ../PatientQueue/lib/StanfordCPPLib/util/timer.cpp
HeapPatientQueue.o: ../PatientQueue/src/HeapPatientQueue.cpp ../PatientQueue/src/HeapPatientQueue.h \
../PatientQueue/src/patientnode.h \
../PatientQueue/src/patientqueue.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o HeapPatientQueue.o ../PatientQueue/src/HeapPatientQueue.cpp
hospital.o: ../PatientQueue/src/hospital.cpp ../PatientQueue/lib/StanfordCPPLib/io/console.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/io/simpio.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/src/HeapPatientQueue.h \
../PatientQueue/src/patientnode.h \
../PatientQueue/src/patientqueue.h \
../PatientQueue/src/VectorPatientQueue.h \
../PatientQueue/src/LinkedListPatientQueue.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o hospital.o ../PatientQueue/src/hospital.cpp
LinkedListPatientQueue.o: ../PatientQueue/src/LinkedListPatientQueue.cpp ../PatientQueue/src/LinkedListPatientQueue.h \
../PatientQueue/src/patientnode.h \
../PatientQueue/src/patientqueue.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o LinkedListPatientQueue.o ../PatientQueue/src/LinkedListPatientQueue.cpp
patientnode.o: ../PatientQueue/src/patientnode.cpp ../PatientQueue/src/patientnode.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o patientnode.o ../PatientQueue/src/patientnode.cpp
VectorPatientQueue.o: ../PatientQueue/src/VectorPatientQueue.cpp ../PatientQueue/src/VectorPatientQueue.h \
../PatientQueue/lib/StanfordCPPLib/collections/vector.h \
../PatientQueue/lib/StanfordCPPLib/collections/collections.h \
../PatientQueue/lib/StanfordCPPLib/system/error.h \
../PatientQueue/lib/StanfordCPPLib/private/init.h \
../PatientQueue/lib/StanfordCPPLib/util/gmath.h \
../PatientQueue/lib/StanfordCPPLib/graphics/gtypes.h \
../PatientQueue/lib/StanfordCPPLib/collections/hashcode.h \
../PatientQueue/lib/StanfordCPPLib/util/random.h \
../PatientQueue/lib/StanfordCPPLib/util/strlib.h \
../PatientQueue/src/patientqueue.h \
../PatientQueue/src/patientnode.h
$(CXX) -c $(CXXFLAGS) $(INCPATH) -o VectorPatientQueue.o ../PatientQueue/src/VectorPatientQueue.cpp
####### Install
install: FORCE
uninstall: FORCE
FORCE:
<file_sep>/*
* File: fractals.cpp
* --------------------------
* Name:
* Section leader:
* This file contains fractal problems for CS106B.
*/
#include "fractals.h"
#include <cmath>
using namespace std;
void drawTreeHelper(GWindow &gw, double x, double y, double size, double angle, int currentOrder, int order);
const int LEAF_COLOR = 0x2e8b57; /* Color of all leaves of recursive tree (level 1) */
const int BRANCH_COLOR = 0x8b7765; /* Color of all branches of recursive tree (level >=2) */
/**
* Draws a Sierpinski triangle of the specified size and order, placing its
* top-left corner at position (x, y).
*
* This will be called by fractalgui.cpp.
*
* @param gw - The window in which to draw the Sierpinski triangle.
* @param x - The x coordinate of the top-left corner of the triangle.
* @param y - The y coordinate of the top-left corner of the triangle.
* @param size - The length of one side of the triangle.
* @param order - The order of the fractal.
*/
void drawSierpinskiTriangle(GWindow& gw, double x, double y, double size, int order) {
// TODO: write this function
if(order == 1){
// top edge
gw.drawLine(x, y, x+size, y);
// left edge
gw.drawLine(x, y, x+size/2, y+size*sqrt(3)/2);
// right edge
gw.drawLine(x+size/2, y+size*sqrt(3)/2, x+size, y);
} else{
// Draw first triangle
drawSierpinskiTriangle(gw, x, y, size/2, order-1);
// Draw second triangle
drawSierpinskiTriangle(gw, x+size/2, y, size/2, order-1);
// Draw third triangle
drawSierpinskiTriangle(gw, x+size/4, y+size*sqrt(3)/4, size/2, order-1);
}
}
/**
* Draws a recursive tree fractal image of the specified size and order,
* placing the bounding box's top-left corner at position (x,y).
*
* This will be called by fractalgui.cpp.
*
* @param gw - The window in which to draw the recursive tree.
* @param x - The x coordinate of the top-left corner of the bounding box.
* @param y - The y coordinate of the top-left corner of the bounding box.
* @param size - The length of one side of the bounding box.
* @param order - The order of the fractal.
*/
void drawTree(GWindow& gw, double x, double y, double size, int order) {
// use a helper function
// draws square boundary
/*
gw.drawLine(x, y, x+size, y);
gw.drawLine(x+size, y, x+size, y+size);
gw.drawLine(x+size, y+size, x, y+size);
gw.drawLine(x, y+size, x, y);
*/
drawTreeHelper(gw, x, y, size, 0, 1, order);
}
void drawTreeHelper(GWindow& gw, double x, double y, double size, double angle, int currentOrder, int order){
if(currentOrder == 1){
if(order == currentOrder){
gw.setColor("#2e8b57");
} else{
gw.setColor("#8b7765");
}
// gets called first
gw.drawLine(x+size/2, y+size, x+size/2, y+size/2);
drawTreeHelper(gw, x+size/2, y+size/2, size/4, 0, currentOrder+1, order);
} else if(currentOrder > order){
// if reached final order, do nothing
} else{
for(int i=0;i<7;i++){
if(currentOrder == order){
// if final order, color should be green.
gw.setColor("#2e8b57");
} else{
gw.setColor("#8b7765");
}
int theta = 45 + (15*i) + angle;
gw.drawPolarLine(x, y, size, theta);
//cout << gw.getColor() << " " << currentOrder << endl;
drawTreeHelper(gw, x + size * cos(theta*M_PI/180), y - size * sin(theta*M_PI/180), size/2, (theta-90), currentOrder+1, order);
}
}
}
/**
* Draws a Mandelbrot Set in the graphical window give, with maxIterations
* (size in GUI) and in a given color (zero for palette)
*
* This will be called by fractalgui.cpp.
*
* @param gw - The window in which to draw the Mandelbrot set.
* @param minX - left-most column of grid
* @param incX - increment value of columns of grid
* @param minY - top-most row of grid
* @param incY - increment value of rows of grid
* @param maxIterations - The maximum number of iterations to run recursive step
* @param color - The color of the fractal; zero if palette is to be used
*/
void mandelbrotSet(GWindow& gw, double minX, double incX,
double minY, double incY, int maxIterations, int color) {
// Creates palette of colors
// To use palette:
// pixels[r][c] = palette[numIterations % palette.size()];
Vector<int> palette = setPalette();
int width = gw.getCanvasWidth();
int height = gw.getCanvasHeight();
GBufferedImage image(width,height,0xffffff);
gw.add(&image);
Grid<int> pixels = image.toGrid(); // Convert image to grid
cout << width << height << endl;
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
Complex coord = Complex(minX+i*incX, minY+j*incY);
int iter = mandelbrotSetIterations(coord, maxIterations);
cout << iter << endl;
if(iter == maxIterations){
pixels[j][i] = palette[iter % palette.size()];
}
}
}
image.fromGrid(pixels); // Converts and puts the grid back into the image
}
/**
* Runs the Mandelbrot Set recursive formula on complex number c a maximum
* of maxIterations times.
*
* This will be called by you. Think about how this fits with the other two functions.
*
* @param c - Complex number to use for recursive formula.
* @param maxIterations - The maximum number of iterations to run recursive step
* @return number of iterations needed to determine if c is unbounded
*/
int mandelbrotSetIterations(Complex c, int maxIterations) {
Complex z;
int iter;
iter = mandelbrotSetIterations(z, c, maxIterations);
if(iter == -1){
return maxIterations;
} else{
return iter;
}
return 0;
}
/**
* An iteration of the Mandelbrot Set recursive formula with given values z and c, to
* run for a maximum of maxIterations.
*
* This will be called by you. Think about how this fits with the other two functions.
*
* @param z - Complex number for a given number of iterations
* @param c - Complex number to use for recursive formula.
* @param remainingIterations - The remaining number of iterations to run recursive step
* @return number of iterations needed to determine if c is unbounded
*/
int mandelbrotSetIterations(Complex z, Complex c, int remainingIterations) {
if(remainingIterations == 0){
return -1;
} else if(z.abs() > 4 ){
return remainingIterations;
} else{
z = z*z + c;
mandelbrotSetIterations(z, c, remainingIterations-1);
}
}
// Helper function to set the palette
Vector<int> setPalette() {
Vector<int> colors;
// Feel free to replace with any palette.
// You can find palettes at:
// http://www.colourlovers.com/palettes
// Example palettes:
// http://www.colourlovers.com/palette/4480793/in_the_middle
// string colorSt = "#A0B965,#908F84,#BF3C43,#9D8E70,#C9BE91,#A0B965,#908F84,#BF3C43";
// http://www.colourlovers.com/palette/4480786/Classy_Glass
// string colorSt = "#9AB0E9,#C47624,#25269A,#B72202,#00002E,#9AB0E9,#C47624,#25269A";
// The following is the "Hope" palette:
// http://www.colourlovers.com/palette/524048/Hope
string colorSt = "#04182B,#5A8C8C,#F2D99D,#738585,#AB1111,#04182B,#5A8C8C,#F2D99D";
Vector<string>colorsStrVec = stringSplit(colorSt,",");
for (string color : colorsStrVec) {
colors.add(convertColorToRGB(trim(color)));
}
return colors;
}
<file_sep>#include "Package.h"
#include <string>
using namespace std;
Package::Package(Customer& sender, Customer& recipient, double weight, double costPerOunce)
: sender{sender}, recipient{recipient}, weight{weight}, costPerOunce{costPerOunce}{
/* empty body */
}
Package::Package(string nameSender, string addressSender, string citySender, string zipcodeSender,
string nameRecipient, string addressRecipient, string cityRecipient, string zipcodeRecipient,
double weight, double costPerOunce)
: sender{Customer{nameSender, addressSender, citySender, zipcodeSender}},
recipient{Customer{nameRecipient, addressRecipient, cityRecipient, zipcodeRecipient}},
weight{weight}, costPerOunce{costPerOunce}{
/* empty body */
}
double Package::getWeight() const{
return weight;
}
double Package::getCostPerOunce() const{
return costPerOunce;
}
double Package::calculateCost() const{
return (weight * costPerOunce);
}
void Package::setWeight(double weight){
this->weight = weight;
}
void Package::setCostPerOunce(double costPerOunce){
this->costPerOunce = costPerOunce;
}
| 8a53b13ce0bd8e18e0e65d09f619a3ea28fe4b4c | [
"Makefile",
"C++"
] | 56 | C++ | jaewook-ryu/Cpp-Study | 113ac2cfec2e761b73fc5bb37be2e362b2976e82 | c57c26b38498690467e48e2a0d7dfc55b5ed1fab | |
refs/heads/main | <file_sep>"# repositorio-de-pruba"
"# repositorio-de-pruba"
System.ot.println("hello every body, here my new git code hahahaha")
System.out.println("if u want, u can say something here, to say hello, and practice a little bit")
"# segundo_ensayo"
"# alpha-airosft-team"
<file_sep>print("primer linea de mi ensayo con python")
| dc54f181fe0b13297abc5e748f4da5048f14f5b7 | [
"Markdown",
"Python"
] | 2 | Markdown | jhonm96/repositorio-de-pruba | d5d17fb5ba444bf4a8cb0ac3daf9c883db480b3e | f89e13e53144e1dcb28c8fb0019e092be82e7615 | |
refs/heads/master | <file_sep>import os
print('Preview your local Jekyll site in your web browser at http://localhost:4000.')
os.system('bundle update')
os.system('bundle exec jekyll serve') | 8cd346455a46855f4a8a894a346e00c83d393244 | [
"Python"
] | 1 | Python | redsriracha/redsriracha.github.io | a7f8ef6aa45993301a899365f529964484b903f1 | d1a6d51d981a9bb707808611a2ef472df4e53828 | |
refs/heads/master | <repo_name>GonzaloCarcamo/prueba_sql<file_sep>/consulta1.sql
--CONSULTA 1: ¿Que cliente realizó la compra más cara?
SELECT customer_name FROM customers, facs
WHERE total_value IN (SELECT MAX(total_value) FROM facs) AND customers.id = facs.customer_id;
<file_sep>/consulta3.sql
--CONSULTA 3: ¿Cuantos clientes han comprado el producto 6?
SELECT COUNT(id_product) FROM facs_prods WHERE id_product = 6 ;
<file_sep>/prueba.sql
--CREAR BASE DE DATOS
CREATE DATABASE prueba;
--CONECTARSE A BASE DE DATOS
\c prueba
--CREAR TABLAS
CREATE TABLE customers(
id SERIAL, customer_name VARCHAR(15), rut VARCHAR(12), address VARCHAR(20), PRIMARY KEY(id));
CREATE TABLE categories(id VARCHAR(5), category_name VARCHAR(15), category_description VARCHAR(30));
CREATE TABLE products(id SERIAL, product_name VARCHAR(15), product_description VARCHAR(40),
value INT, category_id VARCHAR(5));
CREATE TABLE facs(
fac_number SERIAL, fac_date DATE, subtotal INT, iva INT, total_value INT, customer_id INT,
PRIMARY KEY(fac_number), FOREIGN KEY(customer_id) REFERENCES customers(id));
CREATE TABLE facs_prods(
id_register INT, product_name VARCHAR(15), value INT, quantity INT, subtotal INT, fac_id INT);
--POBLAMIENTO DE TABLAS
INSERT INTO customers (customer_name, rut, address) VALUES ('ripley', '76.000.001-1', 'huerfanos 10'),
('falabella', '76.000.002-2', 'estado 20'), ('paris', '76.000.003-3', 'agustinas 30'),('tricot', '76.000.004-4', 'morande 40'),
('hites', '76.000.005-5', 'monjitas 50');
INSERT INTO categories (id, category_name, category_description) VALUES ('100', 'cuerdas', 'instrumentos_de_cuerda'),
('101', 'vientos', 'instrumentos_de_viento'), ('102', 'audio', 'articulos_grabacion');
INSERT INTO facs (fac_date, subtotal, iva, total_value, customer_id) VALUES ('2020-01-01', '200000', '38000', '238000', '1'),
('2020-01-02', '450000', '85500', '535500', '1'), ('2020-01-03', '210000', '39900', '249900', '2'),
('2020-01-04', '100000', '19000', '119000', '2'), ('2020-01-05', '360000', '68400', '428400', '2'),
('2020-01-06', '20000', '3800', '23800', '3'), ('2020-01-07', '400000', '76000', '476000', '4'),
('2020-01-08', '60000', '11400', '71400', '4'), ('2020-01-09', '400000', '76000', '476000', '4'),
('2020-01-10', '100000', '19000', '119000', '4');
INSERT INTO products (product_name, product_description, value, category_id) VALUES ('guitarra', 'instrumento_seis_cuerdas',
'100000', '100'), ('saxo', 'instrumento_vientos', '150000', '101'), ('bajo', 'instrumento_cuatro_cuerdas', '100000', '100'),
('banjo', 'instrumento_cuerdas', '70000', '100'), ('mixer', 'mesa_mezcla', '50000', '102'), ('interfaz', 'tarjeta_sonido',
'120000', '102'), ('audifonos', 'monitoreo_mezcla', '20000', '102'), ('trompeta', 'instrumento_vientos', '200000', '101');
INSERT INTO facs_prods (id_register, product_name, value, quantity, subtotal, fac_id) VALUES (
'1', 'guitarra', '100000', '2', '200000', '1'),(
'2', 'saxo', '150000', '3', '450000', '2'),(
'4', 'banjo', '70000', '3', '210000', '3'),(
'5', 'mixer', '50000', '2', '100000', '4'),(
'6', 'interfaz', '120000', '3', '360000', '5'),(
'7', 'audifonos', '20000', '1', '20000', '6'),(
'8', 'trompeta', '200000', '2', '400000', '7'),(
'7', 'audifonos', '20000', '3', '60000', '8'),(
'3', 'bajo', '100000', '4', '400000', '9'),(
'1', 'guitarra', '100000', '1', '100000', '10');
--AGREGAR PK Y FK
ALTER TABLE categories ADD PRIMARY KEY(id);
ALTER TABLE products ADD PRIMARY KEY(id);
ALTER TABLE products ADD FOREIGN KEY(category_id) REFERENCES categories(id);
ALTER TABLE facs_prods ADD FOREIGN KEY(fac_id) REFERENCES facs(fac_number);
ALTER TABLE facs_prods ADD FOREIGN KEY(id_register) REFERENCES products(id);
ALTER TABLE facs_prods ADD FOREIGN KEY(id_register) REFERENCES products(id);
ALTER TABLE facs_prods RENAME COLUMN id_register TO id_product;
<file_sep>/consulta2.sql
--CONSULTA 2: ¿Que cliente pagó sobre 100.000 de monto?
SELECT distinct (customer_name) FROM customers, facs
WHERE customers.id = facs.customer_id AND facs.total_value > 100000;
| d81bd6cc9726ef79b650f4a9633c5ead1a632042 | [
"SQL"
] | 4 | SQL | GonzaloCarcamo/prueba_sql | 86c55ee53537f0d83e69b3c524ed48b71a381dde | 1ef45dfc803fac41cb1ee8af98e483233aa62b21 | |
refs/heads/master | <repo_name>oliviercm/npcweaponsbase<file_sep>/lua/weapons/swep_ai_base/ai_translations.lua
function SWEP:SetupWeaponHoldTypeForAI(t)
local owner = self:GetOwner()
local cl = owner:GetClass()
self.ActivityTranslateAI = {}
if t == "ar2" then
if GetConVar("npc_weapons_force_animations"):GetBool() then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_AR2
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_AR2_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_AR2_LOW
elseif cl == "npc_combine_s" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_AR2
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_AR2_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_AR2_LOW
elseif cl == "npc_citizen" or cl == "npc_alyx" or cl == "npc_barney" or cl == "npc_monk" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_AR2
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_metropolice" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SMG1
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_COVER_SMG1_LOW
end
elseif t == "smg" then
if GetConVar("npc_weapons_force_animations"):GetBool() then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SMG1
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_combine_s" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SMG1
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_citizen" or cl == "npc_alyx" or cl == "npc_barney" or cl == "npc_monk" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SMG1
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_metropolice" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SMG1
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_COVER_SMG1_LOW
end
elseif t == "pistol" then
if GetConVar("npc_weapons_force_animations"):GetBool() then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_PISTOL
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_PISTOL
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_PISTOL_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_PISTOL_LOW
elseif cl == "npc_combine_s" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_PISTOL
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_AR2
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_AR2_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_AR2_LOW
elseif (cl == "npc_citizen" and string.find(owner:GetModel(), "female")) or cl == "npc_alyx" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_PISTOL
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_PISTOL
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_citizen" or cl == "npc_barney" or cl == "npc_monk" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_PISTOL
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_PISTOL
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_PISTOL_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_metropolice" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_PISTOL
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_PISTOL
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_PISTOL_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_PISTOL_LOW
end
elseif t == "shotgun" then
if GetConVar("npc_weapons_force_animations"):GetBool() then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SHOTGUN
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SHOTGUN_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SHOTGUN
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SHOTGUN_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_combine_s" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SHOTGUN
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SHOTGUN_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SHOTGUN
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SHOTGUN_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_AR2_LOW
elseif cl == "npc_citizen" or cl == "npc_alyx" or cl == "npc_monk" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SHOTGUN
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_SHOTGUN
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SHOTGUN
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SHOTGUN
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SHOTGUN_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_barney" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SHOTGUN
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SHOTGUN
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_metropolice" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_SMG1
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_COVER_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_COVER_SMG1_LOW
end
elseif t == "rpg" then
if GetConVar("npc_weapons_force_animations"):GetBool() then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_RPG
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_AR2_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_LOW_RPG
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_AR2_LOW
elseif cl == "npc_combine_s" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_SMG1
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_AR2
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_AR2_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_AR2_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_AR2_LOW
elseif cl == "npc_citizen" or cl == "npc_alyx" or cl == "npc_barney" or cl == "npc_monk" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_RPG
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_RIFLE_STIMULATED
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_CROUCH_AIM_RIFLE
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_RPG
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_SMG1_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_SMG1_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_SMG1_LOW
elseif cl == "npc_metropolice" then
self.ActivityTranslateAI[ACT_IDLE] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_ANGRY] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_RELAXED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STIMULATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_AGITATED] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_IDLE_AIM_STEALTH] = ACT_IDLE_ANGRY_PISTOL
self.ActivityTranslateAI[ACT_WALK] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_RELAXED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STIMULATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_AGITATED] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_AIM_STEALTH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_CROUCH] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_WALK_CROUCH_AIM] = ACT_WALK_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_RELAXED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STIMULATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_AGITATED] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_AIM_STEALTH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_CROUCH] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RUN_CROUCH_AIM] = ACT_RUN_AIM_PISTOL
self.ActivityTranslateAI[ACT_RELOAD] = ACT_RELOAD_SMG1
self.ActivityTranslateAI[ACT_RELOAD_LOW] = ACT_RELOAD_SMG1_LOW
self.ActivityTranslateAI[ACT_RANGE_ATTACK1] = ACT_RANGE_ATTACK_PISTOL
self.ActivityTranslateAI[ACT_RANGE_ATTACK1_LOW] = ACT_RANGE_ATTACK_PISTOL_LOW
self.ActivityTranslateAI[ACT_COVER_LOW] = ACT_COVER_PISTOL_LOW
self.ActivityTranslateAI[ACT_RANGE_AIM_LOW] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_STIMULATED] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AIM_STIMULATED] = ACT_RANGE_AIM_PISTOL_LOW
self.ActivityTranslateAI[ACT_CROUCHIDLE_AGITATED] = ACT_RANGE_AIM_PISTOL_LOW
end
end
end<file_sep>/lua/entities/ai_generic_projectile/shared.lua
ENT.Base = "base_gmodentity"
ENT.PrintName = "ai_generic_projectile"
ENT.Author = "xyzzy"
ENT.Contact = "https://steamcommunity.com/id/theRealXyzzy/"
ENT.Purpose = ""
ENT.Category = "NPC Weapons"
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.Model = ""
ENT.Speed = 100
ENT.Acceleration = 0
ENT.Damage = 0
ENT.Force = 0
ENT.DamageType = DMG_GENERIC
ENT.HitEffect = { Name = "" }
ENT.HitSound = { Sound = "" }<file_sep>/lua/autorun/sh_npcweapons_constants.lua
NPC_WEAPONS_SNDLVL_GUNFIRE = 75
NPC_WEAPONS_SNDLVL_SUPPRESSED_GUNFIRE = 75
NPC_WEAPONS_SNDLVL_NORM = 75
NPC_WEAPONS_SNDLVL_RELOAD = 75
NPC_WEAPONS_PITCH_GUNFIRE = {95, 105}
NPC_WEAPONS_PITCH_NORM = 100
NPC_WEAPONS_VOLUME_MAX = 1
NPC_WEAPONS_VOLUME_BOLT = 0.4
NPC_WEAPONS_VOLUME_SUPPRESSED = 0.6
NPC_WEAPONS_VOLUME_RELOAD = 0.4<file_sep>/README.md
# Steam Workshop Link
For more information, click the following link:
https://steamcommunity.com/sharedfiles/filedetails/?id=2209643429
## Author
https://steamcommunity.com/id/theRealXyzzy/<file_sep>/lua/weapons/swep_ai_random_base/shared.lua
--Use this as a base class for making a "Random Weapon" weapon that will give NPCs a random weapon from a list when they are spawned with it.
--Example:
--
--
--/lua/weapons/my_random_weapon/shared.lua
--
--DEFINE_BASECLASS("swep_ai_random_base")
--SWEP.WeaponList = {"swep_ai_myweapon1", "swep_ai_myweapon2"}
--
--
--This 2 line weapon class will give NPCs who spawn with it a random weapon from the list, which in this case is either swep_ai_myweapon1 or swep_ai_myweapon2.
SWEP.PrintName = "NPC Random Weapon Base"
SWEP.Author = "xyzzy"
SWEP.Contact = "https://steamcommunity.com/id/theRealXyzzy/"
SWEP.Category = "NPC Weapons"
SWEP.IsNPCWeapon = true
SWEP.WeaponList = {"swep_ai_base"}
function SWEP:Initialize()
if SERVER then
self:Remove()
end
end
function SWEP:OnRemove()
if SERVER and IsValid(self) then
local owner = self:GetOwner()
if IsValid(owner) and owner:IsNPC() then
owner:Give(self.WeaponList[math.random(#self.WeaponList)])
end
end
end<file_sep>/lua/entities/ai_generic_projectile/init.lua
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel(self.Model or "models/weapons/w_missile.mdl")
self:SetModelScale(self.ModelScale or 1)
self:PhysicsInitBox(self:GetModelBounds())
local phys = self:GetPhysicsObject()
if IsValid(phys) then
phys:AddGameFlag(FVPHYSICS_NO_IMPACT_DMG + FVPHYSICS_NO_PLAYER_PICKUP)
phys:EnableGravity(false)
phys:EnableDrag(false)
phys:Wake()
phys:SetVelocity(self:GetForward() * (self.Speed or 0))
phys:AddAngleVelocity(Vector((self.RotationSpeed or 0), 0, 0))
end
if self.Trail then
local trail = util.SpriteTrail(self, self.Trail.Attachment or 0, self.Trail.Color or Color(255, 255, 255, 255), self.Trail.Additive or true, self.Trail.StartWidth or 1, self.Trail.EndWidth or 0, self.Trail.Lifetime or 1, self.Trail.TextureRes or 0, self.Trail.Texture or "trails/smoke.vmt")
end
if self.LoopingSound then
self:EmitSound(self.LoopingSound)
end
end
function ENT:Think()
local phys = self:GetPhysicsObject()
phys:AddVelocity(self:GetForward() * (self.Acceleration or 0))
end
function ENT:PhysicsCollide(data, physobj)
self.HitPos = data.HitPos
if self.IsExplosive then
local projPos = self:WorldSpaceCenter()
local radius = self.ExplosionRadius or 0
for k, v in pairs(ents.FindInSphere(projPos, radius)) do
if IsValid(v) and v:GetPhysicsObject() and self:Visible(v) then
local victimPos = v:WorldSpaceCenter()
local distance = projPos:Distance(victimPos)
local maxDamage = (self.Damage or 0) * GetConVar("npc_weapons_damage_mult"):GetFloat()
local damage = Lerp(distance / radius, maxDamage, 0)
local direction = (victimPos - projPos):GetNormalized()
local owner = self:GetOwner()
local dmginfo = DamageInfo()
if IsValid(owner) then
dmginfo:SetAttacker(owner)
else
dmginfo:SetAttacker(self)
end
dmginfo:SetDamage(damage)
dmginfo:SetDamageType(self.DamageType or DMG_BLAST)
dmginfo:SetDamageForce(direction * damage * damage * self.Force)
dmginfo:SetDamagePosition(self.HitPos)
v:TakeDamageInfo(dmginfo)
end
end
else
local hitEnt = data.HitEntity
if IsValid(hitEnt) then
local dmginfo = DamageInfo()
local owner = self:GetOwner()
if IsValid(owner) then
dmginfo:SetAttacker(owner)
else
dmginfo:SetAttacker(self)
end
dmginfo:SetDamage((self.Damage or 0) * GetConVar("npc_weapons_damage_mult"):GetFloat())
dmginfo:SetDamageForce(self:GetForward() * self.Force)
dmginfo:SetDamageType(self.DamageType or DMG_GENERIC)
dmginfo:SetDamagePosition(self.HitPos)
hitEnt:TakeDamageInfo(dmginfo)
end
end
if self.HitSound then
self:EmitSound(Sound(self.HitSound.Sound), self.HitSound.Level or 75, self.HitSound.Pitch or 100, self.HitSound.Volume or 1, self.HitSound.Channel or CHAN_AUTO)
end
if self.HitEffect then
local hitEffect = EffectData()
hitEffect:SetStart(self.HitPos or self:WorldSpaceCenter())
hitEffect:SetOrigin(self.HitPos or self:WorldSpaceCenter())
hitEffect:SetScale(self.HitEffect.Scale or 1)
hitEffect:SetMagnitude(self.HitEffect.Magnitude or 1)
hitEffect:SetRadius(self.HitEffect.Radius or 1)
hitEffect:SetEntity(hitEnt)
local effectNormal = self.HitEffect.ReverseForward and self:GetForward() or self:GetForward() * -1
hitEffect:SetAngles(effectNormal:Angle())
hitEffect:SetNormal(effectNormal)
util.Effect(self.HitEffect.Name or "", hitEffect)
end
if self.HitWorldEffect then
if data.HitEntity:IsWorld() then
local hitEffect = EffectData()
hitEffect:SetStart(self.HitPos or self:WorldSpaceCenter())
hitEffect:SetOrigin(self.HitPos or self:WorldSpaceCenter())
hitEffect:SetScale(self.HitWorldEffect.Scale or 1)
hitEffect:SetMagnitude(self.HitWorldEffect.Magnitude or 1)
hitEffect:SetRadius(self.HitWorldEffect.Radius or 1)
hitEffect:SetEntity(hitEnt)
local effectNormal = self.HitWorldEffect.ReverseForward and self:GetForward() or self:GetForward() * -1
hitEffect:SetAngles(effectNormal:Angle())
hitEffect:SetNormal(effectNormal)
util.Effect(self.HitWorldEffect.Name or "", hitEffect)
elseif self.HitWorldEffect.TraceThrough then
local traceData = {}
traceData.start = self.HitPos
traceData.endpos = self.HitPos + self:GetForward() * self.HitWorldEffect.TraceThrough
traceData.mask = MASK_NPCWORLDSTATIC
local trace = util.TraceLine(traceData)
if trace.Entity:IsWorld() then
local hitEffect = EffectData()
hitEffect:SetStart(trace.HitPos)
hitEffect:SetOrigin(trace.HitPos)
hitEffect:SetScale(self.HitWorldEffect.Scale or 1)
hitEffect:SetMagnitude(self.HitWorldEffect.Magnitude or 1)
hitEffect:SetRadius(self.HitWorldEffect.Radius or 1)
hitEffect:SetEntity(hitEnt)
local effectNormal = self.HitWorldEffect.ReverseForward and self:GetForward() or self:GetForward() * -1
hitEffect:SetAngles(effectNormal:Angle())
hitEffect:SetNormal(effectNormal)
util.Effect(self.HitWorldEffect.Name or "", hitEffect)
end
end
end
if self.ImpactDecal then
util.Decal(self.ImpactDecal, data.HitPos - data.HitNormal, data.HitPos + data.HitNormal)
end
self:Remove()
end
function ENT:OnRemove()
if self.LoopingSound then
self:StopSound(self.LoopingSound)
end
end<file_sep>/lua/autorun/client/cl_npcweapons_toolmenu.lua
hook.Add("PopulateToolMenu", "NPC Weapons Options", function()
spawnmenu.AddToolMenuOption("Options", "NPC Weapons", "NPC Weapons Options", "Options", "", "", function(dform)
dform:NumSlider("Damage Multiplier", "npc_weapons_damage_mult", 0.01, 2, 2)
dform:ControlHelp("Damage Multiplier: NPC Weapon damage will be multiplied by this number.")
dform:CheckBox("Force Animations", "npc_weapons_force_animations")
dform:ControlHelp("Force Animations: Force NPCs to use the right animations even if they don't support them by default. This will NOT work without an addon that replaces NPC animations, and even then it might not work perfectly if the addon doesn't replace the right animations.")
end)
end)<file_sep>/lua/autorun/server/sv_npcweapons_constants.lua
NPC_WEAPONS_MIN_AIM_DELAY_NONE = 0.00
NPC_WEAPONS_MAX_AIM_DELAY_NONE = 0.00
NPC_WEAPONS_MIN_AIM_DELAY_LOW = 0.25
NPC_WEAPONS_MAX_AIM_DELAY_LOW = 0.50
NPC_WEAPONS_MIN_AIM_DELAY_MED = 0.50
NPC_WEAPONS_MAX_AIM_DELAY_MED = 1.00
NPC_WEAPONS_MIN_AIM_DELAY_HIGH = 1.00
NPC_WEAPONS_MAX_AIM_DELAY_HIGH = 1.50
NPC_WEAPONS_MIN_DROPOFF_DISTANCE_PISTOL = 512
NPC_WEAPONS_MAX_DROPOFF_DISTANCE_PISTOL = 2048
NPC_WEAPONS_MIN_DROPOFF_DISTANCE_SMG = 512
NPC_WEAPONS_MAX_DROPOFF_DISTANCE_SMG = 2048
NPC_WEAPONS_MIN_DROPOFF_DISTANCE_SHOTGUN = 256
NPC_WEAPONS_MAX_DROPOFF_DISTANCE_SHOTGUN = 2048
NPC_WEAPONS_MIN_DROPOFF_DISTANCE_RIFLE = 512
NPC_WEAPONS_MAX_DROPOFF_DISTANCE_RIFLE = 4096
NPC_WEAPONS_MIN_DROPOFF_DISTANCE_SNIPER = 1024
NPC_WEAPONS_MAX_DROPOFF_DISTANCE_SNIPER = 8192
NPC_WEAPONS_SPREAD_MOVE_MULT_NONE = 1.0
NPC_WEAPONS_SPREAD_MOVE_MULT_LOW = 1.1
NPC_WEAPONS_SPREAD_MOVE_MULT_MED = 1.2
NPC_WEAPONS_SPREAD_MOVE_MULT_HIGH = 1.4
NPC_WEAPONS_SPREAD_MOVE_MULT_VHIGH = 5.0
NPC_WEAPONS_RELOAD_TIME_LOW = 1.8
NPC_WEAPONS_RELOAD_TIME_MED = 2.2
NPC_WEAPONS_RELOAD_TIME_HIGH = 2.6<file_sep>/lua/weapons/swep_ai_base/shared.lua
--////////////////
--////Author: xyzzy
--////////////////////////////////////////////////////////////////////////////////
--////This is the base for my NPC weapons.
--////
--////The main content pack using this base is here: https://steamcommunity.com/sharedfiles/filedetails/?id=632126535
--////
--////Do not re-upload, reproduce, copy, modify, alter, or adapt any part of this addon, weapon base, or code without my permission.
--////You are allowed to use this base to make your own NPC weapons, but you CANNOT include any of the files from this addon in your addon, including this base.
--////If your addon needs this base to work, add this addon as a required item: https://steamcommunity.com/sharedfiles/filedetails/?id=2209643429
--////Violating these rules is against Valve's Terms and Conditions (https://store.steampowered.com/subscriber_agreement/#4) and may get your addon removed from the Steam Workshop and your account TERMINATED!
--////
--////If you make an addon using this base, credit me (xyzzy) in the addon's description.
--////
--////This addon and weapon base are not authorized for uploading on Steam or any other file sharing service except by the Steam user xyzzy, under the Steam ID STEAM_0:1:21671914.
--////
--////Copyright © 2016 by xyzzy, All rights reserved.
--////////////////////////////////////////////////////////////////////////////////
SWEP.PrintName = "NPC Weapon Base"
SWEP.Author = "xyzzy"
SWEP.Contact = "https://steamcommunity.com/id/theRealXyzzy/"
SWEP.Category = "NPC Weapons"
SWEP.IsNPCWeapon = true
--////////////////////////////////////////////////////////////////////////////////
--////Usage:
--////
--////Make an weapon that inherits from this base, eg. DEFINE_BASECLASS("swep_ai_base")
--////
--////Then you can configure the following values that start with "SWEP.", eg. SWEP.Primary.DamageMax = 10
--////
--////Most of the time, simply configuring the values below is going to be more than enough to get what you want.
--////
--////In order to help with development, you can use this command to display some debug info on your screen: "developer 1". It requires "sv_cheats" to be enabled.
--////When "developer 1" is enabled, the following information will display:
--////Muzzle position (where the bullet comes from) - Blue cross
--////Target position (where the bullet is aimed towards, without taking spread into account) - Red cross
--////Hit position (where the bullet landed) - Purple cross
--////Muzzle flash (starts at muzzle postion, extends in the direction of the muzzle flash effect) - Green line
--////Shell eject (starts at shell eject postion, extends in the direction of the shell eject effect) - Yellow line
--////Bullet distance, damage, and multipler from damage falloff - Text at the bullet impact position
--////////////////////////////////////////////////////////////////////////////////
--Weapon model and holdtype
SWEP.WorldModel = "models/weapons/w_pistol.mdl" --What model should we use as the world model? This determines where the bullet comes from and where the effects come from.
SWEP.ClientModel = nil --Table used to render clientside models. Useful if you want to display a model that isn't rigged properly for NPCs. The world model is not drawn if a client model exists. { model : String, pos : Vector, angle : Angle, size : Vector, color : Color, skin : Number, bodygroup : Table, bone : String }.
SWEP.HoldType = "pistol" --Which animation set should we use? "pistol": Hold like a pistol. Note that only female citizens, Metropolice, and Alyx have pistol animations, other NPCs will hold it like an SMG. "smg": Hold like an SMG, close to the hip while running. The offhand holds a vertical grip. "ar2": Hold like a rifle, high and at shoulder level. The offhand lays flat (when the NPC has animations for it). "shotgun": Hold low to the hip. Note that reloads will play a shotgun cocking sound if the holder is a female npc_citizen. "rpg": Hold high and on top of the shoulder.
--Muzzle flash effects
SWEP.EnableMuzzleEffect = true --Enable muzzleflash?
SWEP.MuzzleAttachment = "1" --Where the muzzleflash and bullet should come out of on the weapon. Most models have this as 1 or "muzzle".
SWEP.MuzzleEffect = "MuzzleEffect" --Which effect to use as the muzzleflash.
SWEP.MuzzleEffectScale = 1 --Muzzle effect scale.
SWEP.MuzzleEffectRadius = 1 --Muzzle effect radius.
SWEP.MuzzleEffectMagnitude = 1 --Muzzle effect magnitude.
--Shell eject effects
SWEP.EnableShellEffect = true --Enable shell casings?
SWEP.ShellAttachment = "2" --Where the bullet casing should come out of on the weapon. Most models have this as 2.
SWEP.ShellEffect = "ShellEject" --Which effect to use as the bullet casing.
SWEP.ShellEffectScale = 1 --Shell effect scale.
SWEP.ShellEffectRadius = 1 --Shell effect radius.
SWEP.ShellEffectMagnitude = 1 --Shell effect magnitude.
SWEP.ShellEffectDelay = 0 --How long to delay the shell eject for. This is useful if you want to delay ejecting the shell after shooting (eg. pumping a shotgun after shooting, bolt action sniper rifle)
--Tracer effects
SWEP.EnableTracerEffect = true --Enable tracer?
SWEP.TracerEffect = "Tracer" --Which effect to use as the bullet tracer.
SWEP.TracerX = 1 --For every X bullets, show the tracer effect.
--Additional effects (impact decal, additional tracers, additional muzzleflashes, additional effects at the hit position)
SWEP.ImpactDecal = nil --What decal should we display at the impact point? Eg. "Scorch" leaves an explosion scorch at the impact point.
SWEP.ExtraShootEffects = nil --Which extra effects should we use when shooting? This is useful if you want to display extra tracers, hit location effects, extra muzzleflashes, eg. Explosion at impact point: { { EffectName = "Explosion" } } or an extra tracer: { { EffectName = "GunshipTracer" } } or an extra muzzleflash { { EffectName: "ChopperMuzzleFlash" } }. The effects should all be in a table, so for example, if you wanted to use two effects at once: { { EffectName = "Explosion" }, { EffectName = "ChopperMuzzleFlash" } }. You can add the following keys to each effect: "Scale", "Magnitude", "Radius" eg. { EffectName = "Explosion", Magnitude = 1337, Scale = 404, Radius = 80085 }
--Reloading
SWEP.ReloadTime = 0 --How long should reloads last in seconds? NPCs will not be able to fire for this much time after starting a reload.
SWEP.ReloadSounds = nil --Which sounds should we play when the gun is being reloaded? Should be a table of tables of {delay, sound}, eg. {{0.4, "ak47_clipout"}, {1.2, "ak47_clipin"}}. I highly recommend you use a soundscript here instead of a path to a raw sound file. Also, I recommend using CHAN_AUTO instead of CHAN_WEAPON here or your reload sound will stop and overwrite firing sounds (cutting them off), making it sound bad.
--Weapon firing sounds (gunshot, shotgun pumping, rifle bolting, etc)
SWEP.Primary.Sound = "weapons/pistol/pistol_fire2.wav" --What gunshot sound should we play when the gun fires? If you use a table eg. {"sound_1", "sound_2", "sound_3"}, a random sound from the table will be chosen. I recommend using soundscripts instead of a path to a raw sound file. I also recommend using CHAN_WEAPON as the audio channel.
SWEP.Primary.ExtraSounds = nil --What extra sounds should we play after firing? This shouldn't be for the gunshot sound, but for stuff like pumping a shotgun slide or bolt action sounds. Should be a table of tables of {delay, sound}, eg. {{0.4, "bolt_back"}, {1.2, "bolt_forward"}} or {{0.4, "shotgun_pump"}}. I highly recommend you use soundscripts here instead of a path to a raw sound file so you can control the volume of the sound, etc.
--Weapon stats
SWEP.Primary.Type = "bullet" --"bullet", "projectile". Projectile can be explosive (rockets) or non-explosive.
SWEP.Primary.DamageType = DMG_BULLET --The damage type of the weapon. https://wiki.facepunch.com/gmod/Enums/DMG
SWEP.Primary.DamageMin = 0 --How much minimum damage each bullet should do. Rule of thumb is average damage should be around 4-8 for small caliber weapons like pistols, 8-12 for medium caliber weapons like rifles, and 15+ for large caliber weapons like sniper rifles.
SWEP.Primary.DamageMax = 0 --How much maximum damage each bullet should do. Rule of thumb is average damage should be around 4-8 for small caliber weapons like pistols, 8-12 for medium caliber weapons like rifles, and 15+ for large caliber weapons like sniper rifles.
SWEP.Primary.MinDropoffDistance = 0 --The minimum distance before damage begins to drop off.
SWEP.Primary.MaxDropoffDistance = 1 --The maximum distance before damage drops off to the minimum damage.
SWEP.Primary.MaxDropoffFactor = 0.2 --The factor to multiply damage by when distance is equal to or more than the max dropoff distance.
SWEP.Primary.Force = 0 --How much force each bullet should do. Rule of thumb is set this as the average damage, but it should stay between 5 - 15. You usually don't want to go outside that range, otherwise bodies get thrown too soft/hard.
SWEP.Primary.Spread = 0 --How inaccurate the weapon should be. Examples: AWP - 0.003, M4A1 - 0.030, MAC10 - 0.060. Spread acts differently for projectile weapons, you need a higher value to get the same amount of spread.
SWEP.Primary.SpreadMoveMult = 0 --How much should we multiply the spread if the NPC is moving? Higher values mean the weapon is more inaccurate while moving. Rule of thumb is 1.2 for rifles, 1.1 for pistols, 1 for SMGs, 1.3-1.5 for MGs, and 5+ for sniper rifles.
SWEP.Primary.BurstMinShots = 0 --How many times should we shoot in every burst, at minimum?
SWEP.Primary.BurstMaxShots = 0 --How many times should we shoot in every burst, at maximum?
SWEP.Primary.BurstMinDelay = 0 --How much extra time should we wait between bursts, at minimum?
SWEP.Primary.BurstMaxDelay = 0 --How much extra time should we wait between bursts, at maximum?
SWEP.Primary.BurstCancellable = true --Can bursts stop early? If this is false, NPCs will fire the full burst even if their target dies - the rest of the burst will be fired at the last position they shot at. This can look pretty weird if you have a high burst count (5+) so be careful, otherwise the NPC will be shooting air a lot.
SWEP.Primary.FireDelay = 0 --How much time should there be between each shot?
SWEP.Primary.NumBullets = 0 --How many bullets should there be for each shot? Most weapons would have this as 1, but shotguns would have a different value, like 8 or 9. This works for projectile weapons too.
SWEP.Primary.ClipSize = 0 --How many shots should we get per reload?
SWEP.Primary.DefaultClip = 0 --How many shots should the weapon spawn with in the magazine? Usually you want this the same as SWEP.Primary.ClipSize.
SWEP.Primary.AimDelayMin = 0 --How long should we wait before shooting a new enemy, at minimum?
SWEP.Primary.AimDelayMax = 0 --How long should we wait before shooting a new enemy, at maximum?
SWEP.Primary.Ammo = "pistol" --The ammo type of the weapon. This doesn't do anything at the moment, but if picking up these guns is ever implemented then this is the ammo type that you would get.
SWEP.Primary.InfiniteAmmo = false --Should we never have to reload?
--Projectile configuration. Used if SWEP.Primary.Type is "projectile". Note that projectiles don't have damage falloff over distance.
SWEP.ProjectileModel = "models/weapons/w_missile.mdl" --The model to use for the projectile.
SWEP.ProjectileModelScale = 1 --How much to scale the projectile model by.
SWEP.ProjectileStartSpeed = 0 --The speed the projectile starts with.
SWEP.ProjectileAcceleration = 0 --The acceleration of the projectile.
SWEP.ProjectileHitEffect = { Name = "Explosion", Radius = 1, Magnitude = 1, Scale = 1 } --The effect used at the projectile impact location. Keys: "Name" : String, "Radius" : Number, "Magnitude" : Number, "Scale" : Number, "ReverseForward" : Boolean (reverse the angle and normal of the effect)
SWEP.ProjectileHitWorldEffect = nil --The effect used at the projectile impact location, if it hits world. Compared to ProjectileHitEffect, has additional key "TraceThrough" : Number (trace a line of this length from the hit location and place the effect at the trace hit location if it hits world)
SWEP.ProjectileHitSound = nil --The sound played at the projectile impact location, eg. { Sound = "explosion.wav", Level = 75, Pitch = 100, Volume = 1, Channel = CHAN_AUTO }
SWEP.ProjectileLoopingSound = nil --What sound to play as the projectile flies in mid-air, eg. the "woosh" of the projectile.
SWEP.ProjectileRotationSpeed = nil --How quickly the projectile rotates in mid-air.
SWEP.ProjectileIsExplosive = true --If true, damage is dealt as an explosion where damage decreases by distance from the explosion. If false, damage is dealt only to the entity directly hit by the projectile.
SWEP.ProjectileExplosionRadius = 0 --Only used if the projectile is explosive. The radius that damage is dealt. Damage decreases as the target gets farther away from the center of the explosion. Force applied is calculated with the formula: (damage ^ 2) * 10.
SWEP.ProjectileTrail = {
Attachment = 0,
Color = Color(255, 255, 255, 200),
Additive = true,
StartWidth = 5,
EndWidth = 0,
Lifetime = 0.3,
TextureRes = 0,
Texture = "trails/smoke.vmt",
}
--Additional weapon configuration
SWEP.ForceWalking = false --Should NPCs be forced to walk when shooting this weapon?
SWEP.ForceWalkingTime = 0 --How long to force NPCs to walk after shooting.
SWEP.AimAtBody = false --Whether to aim at the body (center of mass) instead of the head. Useful for projectile type weapons. Note that custom SNPCs (VJ Base, etc.) are always targeted at the center of mass anyways.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
----//// Don't touch anything below this line unless you know what you are doing! ////------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SWEP.LastEnemy = nil
SWEP.LastActivity = nil
SWEP.LastTargetPos = nil
SWEP.AimForHeadTable = { --Which entity classes to use HeadTarget() instead of BodyTarget() on. If SWEP.AimAtBody is true, this table won't be used since we're aiming for the body.
player = true,
npc_combine_s = true,
npc_citizen = true,
npc_alyx = true,
npc_barney = true,
npc_monk = true,
npc_eli = true,
npc_kleiner = true,
npc_magnusson = true,
npc_mossman = true,
npc_breen = true,
npc_metropolice = true,
npc_zombie = true,
npc_zombine = true,
}
function SWEP:Initialize()
self:SetHoldType(self.HoldType)
if SERVER then
self:Think()
end
if CLIENT and self.ClientModel then
self:CreateClientModel()
end
end
function SWEP:Equip(owner)
local ownerClass = owner:GetClass()
if owner:IsPlayer() or ownerClass == "npc_vortigaunt" then --For some reason Vortigaunts can spawn with weapons but they can't really use them and it spawns as a crotchgun so lets not let that happen.
self:Remove()
end
end
function SWEP:PrimaryFire()
local currentEnemy = self.LastEnemy
local fireDelay = self.Primary.FireDelay
local burstCount = math.random(self.Primary.BurstMinShots, self.Primary.BurstMaxShots)
local burstDelay = math.Rand(self.Primary.BurstMinDelay, self.Primary.BurstMaxDelay)
for i = 1, burstCount do
timer.Simple((i - 1) * fireDelay, function()
if not IsValid(self) then return end
local owner = self:GetOwner()
if not IsValid(owner) then return end
if not self:CanPrimaryFire() then return end
if not owner:GetEnemy() or owner:GetEnemy() ~= currentEnemy then
if not self.Primary.BurstCancellable and self.LastTargetPos then
self:Shoot(self.LastTargetPos) --If the weapon is configured to not allow stopping bursts, keep firing at the last spot even if the enemy is already dead.
end
return
end
self:Shoot()
end)
end
self:SetNextPrimaryFire(CurTime() + burstCount * fireDelay + burstDelay)
end
function SWEP:Shoot(forceTargetPos) --forceTargetPos is used to force NPCs to shoot at air if their target is already dead but the gun is configured to fire full bursts without stopping
local owner = self:GetOwner()
local enemy = owner:GetEnemy()
local muzzlePos = IsValid(enemy) and owner:GetPos():DistToSqr(enemy:GetPos()) > 16384 and self:GetAttachment(self.MuzzleAttachment).Pos or owner:WorldSpaceCenter()
local targetPos = forceTargetPos
if not targetPos then
local enemyClass = enemy:GetClass()
if !self.AimForBody and self.AimForHeadTable[enemyClass] then
if enemy:IsPlayer() or enemyClass == "npc_combine_s" then -- Special logic for npc_combine_s because NPC:HeadTarget() doesn't return a good position when used on npc_combine_s
local headBone = enemy:LookupBone("ValveBiped.Bip01_Head1")
targetPos = (headBone and enemy:GetBonePosition(headBone)) or enemy:HeadTarget(muzzlePos) or enemy:BodyTarget(muzzlePos) or enemy:WorldSpaceCenter() or enemy:GetPos()
else
targetPos = enemy:HeadTarget(muzzlePos) or enemy:BodyTarget(muzzlePos) or enemy:WorldSpaceCenter() or enemy:GetPos()
end
else
if enemy:IsPlayer() then
targetPos = enemy:WorldSpaceCenter() or enemy:GetPos() -- For some reason Player:BodyTarget() returns the head position so it's not usable here
else
targetPos = enemy:BodyTarget(muzzlePos) or enemy:WorldSpaceCenter() or enemy:GetPos()
end
end
end
self.LastTargetPos = targetPos
if GetConVar("developer"):GetBool() then
debugoverlay.Cross(muzzlePos, 3, 1, Color(0, 0, 255), true)
debugoverlay.Cross(targetPos, 3, 1, Color(255, 0, 0), true)
end
local direction = (targetPos - muzzlePos):GetNormalized()
local spread = owner:IsMoving() and self.Primary.Spread * self.Primary.SpreadMoveMult or self.Primary.Spread
if self.Primary.Type == "bullet" then
local bulletInfo = {}
bulletInfo.Attacker = owner
bulletInfo.Callback = self.FireBulletsCallback
bulletInfo.Damage = math.random(self.Primary.DamageMin, self.Primary.DamageMax) * GetConVar("npc_weapons_damage_mult"):GetFloat()
bulletInfo.Force = self.Primary.Force
bulletInfo.Num = self.Primary.NumBullets
bulletInfo.Tracer = self.TracerX
bulletInfo.TracerName = self.EnableTracerEffect and self.TracerEffect or ""
bulletInfo.AmmoType = self.Primary.Ammo
bulletInfo.Dir = direction
bulletInfo.Spread = Vector(spread, spread, 0)
bulletInfo.Src = muzzlePos
self:FireBullets(bulletInfo)
elseif self.Primary.Type == "projectile" then
local projectiles = {}
for i = 1, self.Primary.NumBullets do
local shootAngle = Vector(targetPos.x - muzzlePos.x, targetPos.y - muzzlePos.y, targetPos.z - muzzlePos.z):Angle()
shootAngle.p = shootAngle.p + math.Rand(-spread, spread)
shootAngle.y = shootAngle.y + math.Rand(-spread, spread)
local projectile = ents.Create("ai_generic_projectile")
projectile:SetPos(muzzlePos)
projectile:SetAngles(shootAngle)
projectile:SetOwner(owner)
projectile.Damage = math.random(self.Primary.DamageMin, self.Primary.DamageMax)
projectile.DamageType = self.Primary.DamageType
projectile.Model = self.ProjectileModel
projectile.ModelScale = self.ProjectileModelScale
projectile.Speed = self.ProjectileStartSpeed
projectile.Acceleration = self.ProjectileAcceleration
projectile.HitEffect = self.ProjectileHitEffect
projectile.HitWorldEffect = self.ProjectileHitWorldEffect
projectile.HitSound = self.ProjectileHitSound
projectile.LoopingSound = self.ProjectileLoopingSound
projectile.RotationSpeed = self.ProjectileRotationSpeed
projectile.IsExplosive = self.ProjectileIsExplosive
projectile.ExplosionRadius = self.ProjectileExplosionRadius
projectile.Trail = self.ProjectileTrail
projectile.ImpactDecal = self.ImpactDecal
projectile:Spawn()
for _, proj in pairs(projectiles) do
constraint.NoCollide(projectile, proj, 0, 0)
end
table.insert(projectiles, projectile)
end
end
self:ShootEffects()
if self.ForceWalking then
owner:SetMovementActivity(ACT_WALK)
self.ForceWalkingUntil = CurTime() + self.ForceWalkingTime
end
if not self.Primary.InfiniteAmmo then
self:TakePrimaryAmmo(1)
end
end
function SWEP:FireBulletsCallback(tr, dmgInfo)
local weapon = self:GetActiveWeapon()
if not IsValid(weapon) then return end
local distance = tr.StartPos:Distance(tr.HitPos)
local dropoff = Lerp((distance - weapon.Primary.MinDropoffDistance) / weapon.Primary.MaxDropoffDistance, 1, weapon.Primary.MaxDropoffFactor)
dmgInfo:ScaleDamage(dropoff)
dmgInfo:SetDamageType(weapon.Primary.DamageType)
for _, shootEffect in ipairs(weapon.ExtraShootEffects or {}) do
local effect = EffectData()
effect:SetEntity(weapon)
effect:SetStart(tr.HitPos)
effect:SetOrigin(tr.HitPos)
effect:SetNormal(tr.HitNormal)
effect:SetAngles(tr.HitNormal:Angle())
effect:SetScale(shootEffect.Scale or 1)
effect:SetRadius(shootEffect.Radius or 1)
effect:SetMagnitude(shootEffect.Magnitude or 1)
effect:SetAttachment(weapon.MuzzleAttachment or 1)
util.Effect(shootEffect.EffectName or "", effect)
end
if weapon.ImpactDecal then
util.Decal(weapon.ImpactDecal, tr.HitPos + tr.HitNormal, tr.HitPos - tr.HitNormal)
end
if GetConVar("developer"):GetBool() then
debugoverlay.Text(tr.HitPos, "DISTANCE: "..math.Round(distance).." MULTIPLIER: "..math.Round(dropoff, 2).." DAMAGE: "..math.Round(dmgInfo:GetDamage()))
debugoverlay.Cross(tr.HitPos, 3, 1, Color(255, 0, 255), true)
end
end
function SWEP:ShootEffects()
self:EmitSound(type(self.Primary.Sound) == "string" and self.Primary.Sound or self.Primary.Sound[math.random(#self.Primary.Sound)])
if self.Primary.ExtraSounds then
for _, v in ipairs(self.Primary.ExtraSounds) do
timer.Simple(v[1], function()
if IsValid(self) then
sound.Play(v[2], self:GetPos())
end
end)
end
end
if self.EnableMuzzleEffect then
local muzzleEffect = EffectData()
local muzzleAttach = self:GetAttachment(self.MuzzleAttachment or 1)
local muzzlePos = muzzleAttach and muzzleAttach.Pos or self:GetPos()
local muzzleForward = muzzleAttach and muzzleAttach.Ang:Forward() or self:GetForward()
local muzzleAngles = muzzleAttach and muzzleAttach.Ang or self:GetAngles()
muzzleEffect:SetEntity(self)
muzzleEffect:SetStart(muzzlePos)
muzzleEffect:SetOrigin(muzzlePos)
muzzleEffect:SetNormal(muzzleForward)
muzzleEffect:SetAngles(muzzleAngles)
muzzleEffect:SetScale(self.MuzzleEffectScale or 1)
muzzleEffect:SetRadius(self.MuzzleEffectRadius or 1)
muzzleEffect:SetMagnitude(self.MuzzleEffectMagnitude or 1)
muzzleEffect:SetAttachment(self.MuzzleAttachment or 1)
util.Effect(self.MuzzleEffect or "", muzzleEffect)
self:GetOwner():MuzzleFlash()
debugoverlay.Line(muzzlePos, muzzlePos + muzzleForward * 16, 1, Color(0, 255, 0))
end
if self.EnableShellEffect then
timer.Simple(self.ShellEffectDelay, function()
if IsValid(self) then
local shellEffect = EffectData()
local shellAttach = self:GetAttachment(self.ShellAttachment or 2)
local shellPos = shellAttach and shellAttach.Pos or self:GetPos()
local shellForward = shellAttach and shellAttach.Ang:Forward() or self:GetForward()
local shellAngles = shellAttach and shellAttach.Ang or self:GetAngles()
shellEffect:SetEntity(self)
shellEffect:SetStart(shellPos)
shellEffect:SetOrigin(shellPos)
shellEffect:SetNormal(shellForward)
shellEffect:SetAngles(shellAngles)
shellEffect:SetScale(self.ShellEffectScale or 1)
shellEffect:SetRadius(self.ShellEffectRadius or 1)
shellEffect:SetMagnitude(self.ShellEffectMagnitude or 1)
shellEffect:SetAttachment(self.ShellAttachment or 2)
util.Effect(self.ShellEffect or "", shellEffect)
debugoverlay.Line(shellPos, shellPos + shellForward * 16, 1, Color(255, 255, 0))
end
end)
end
end
function SWEP:EmitReloadSounds()
if not self.ReloadSounds then return end
for _, v in ipairs(self.ReloadSounds) do
timer.Simple(v[1], function()
if IsValid(self) then
self:EmitSound(v[2])
end
end)
end
end
function SWEP:Think()
timer.Simple(0.01, function()
if IsValid(self) then
self:Think()
end
end)
local owner = self:GetOwner()
if IsValid(owner) and owner:IsNPC() then
local curtime = CurTime()
if self.ForceWalkingUntil and curtime > self.ForceWalkingUntil then
owner:SetMovementActivity(ACT_RUN)
self.ForceWalkingUntil = nil
end
local ownerActivity = owner:GetActivity()
if ownerActivity == ACT_RELOAD and self.LastActivity ~= ACT_RELOAD then
self:SetNextPrimaryFireReload()
self:EmitReloadSounds()
end
self.LastActivity = ownerActivity
local enemy = owner:GetEnemy()
if IsValid(enemy) then
local enemyVisible = owner:Visible(enemy)
if enemy ~= self.LastEnemy or not enemyVisible then
self:SetNextPrimaryFireAimDelay()
self.LastEnemy = enemy
end
local enemyIsAlive = enemy:Health() > 0 and enemy:GetMaxHealth() > 0
if self:GetNextPrimaryFire() <= curtime and self:CanPrimaryFire() and enemyIsAlive and enemyVisible then
self:PrimaryFire()
end
else
self:SetNextPrimaryFireAimDelay()
end
if self:Clip1() <= 0 and not owner:IsCurrentSchedule(SCHED_RELOAD) and not owner:IsCurrentSchedule(SCHED_HIDE_AND_RELOAD) then
owner:SetSchedule(SCHED_RELOAD)
end
end
end
function SWEP:CanPrimaryFire()
local owner = self:GetOwner()
if self:Clip1() <= 0 or owner:GetActivity() == ACT_RELOAD then
return false
end
local enemy = owner:GetEnemy()
if IsValid(enemy) then
local aimDirection = owner:GetAngles().y
local enemyDirection = Vector(enemy:GetPos() - owner:GetPos()):Angle().y
if math.abs(enemyDirection - aimDirection) > 45 then
return false
end
end
return true
end
function SWEP:SetNextPrimaryFireReload()
local reloadtime = CurTime() + self.ReloadTime
if self:GetNextPrimaryFire() <= reloadtime then
self:SetNextPrimaryFire(reloadtime)
end
end
function SWEP:SetNextPrimaryFireAimDelay()
local curtime = CurTime()
if self:GetNextPrimaryFire() <= curtime + self.Primary.AimDelayMax then
local aimtime = math.Rand(self.Primary.AimDelayMin, self.Primary.AimDelayMax)
self:SetNextPrimaryFire(curtime + aimtime)
end
end
function SWEP:DrawWorldModel()
local owner = self:GetOwner()
if not self.ClientModel or not IsValid(owner) then
self:DrawModel()
return
end
local pos, ang = self:GetBoneOrientation(self.ClientModel.bone or "ValveBiped.Bip01_R_Hand", owner)
if !pos then
return
end
local model = self.ClientModelEnt
if not IsValid(model) then
return
end
model:SetPos(pos + ang:Forward() * self.ClientModel.pos.x + ang:Right() * self.ClientModel.pos.y + ang:Up() * self.ClientModel.pos.z)
ang:RotateAroundAxis(ang:Up(), self.ClientModel.angle.y)
ang:RotateAroundAxis(ang:Right(), self.ClientModel.angle.p)
ang:RotateAroundAxis(ang:Forward(), self.ClientModel.angle.r)
model:SetAngles(ang)
local matrix = Matrix()
matrix:Scale(self.ClientModel.size or Vector(1, 1, 1))
model:EnableMatrix("RenderMultiply", matrix)
if self.ClientModel.skin and self.ClientModel.skin ~= model:GetSkin() then
model:SetSkin(self.ClientModel.skin)
end
for k, v in pairs(self.ClientModel.bodygroup or {}) do
model:SetBodygroup(k, v)
end
render.SetColorModulation(self.ClientModel.color.r / 255, self.ClientModel.color.g / 255, self.ClientModel.color.b / 255)
render.SetBlend(self.ClientModel.color.a / 255)
end
function SWEP:CreateClientModel()
if !IsValid(self.ClientModelEnt) then
self.ClientModelEnt = ClientsideModel(self.ClientModel.model, RENDERGROUP_OPAQUE)
self.ClientModelEnt:SetPos(self:GetPos())
self.ClientModelEnt:SetAngles(self:GetAngles())
self.ClientModelEnt:SetParent(self)
end
end
function SWEP:GetBoneOrientation(boneName, ent)
local bone = ent:LookupBone(boneName)
local matrix = bone and ent:GetBoneMatrix(bone) or nil
if matrix then
return matrix:GetTranslation(), matrix:GetAngles()
end
end
function SWEP:GetCapabilities()
return 0 --Prevents weapons from firing animation events (e.g. built-in HL2 guns muzzleflash & shell casings, NPCs "recoiling" from firing the gun)
end
function SWEP:PrimaryAttack()
return
end
function SWEP:SecondaryAttack()
return
end
function SWEP:OnDrop()
self:Remove()
end
function SWEP:OnRemove()
--Something to do with clientside models and PVS, this was the solution I found that prevents a memory leak because models would get stuck and not get garbage collected after leaving the PVS and you have to manually remove them with Remove()
if CLIENT then
if self.ClientModelEnt then
self.ClientModelEnt:Remove()
end
timer.Simple(0, function()
if IsValid(self) then
self:CreateClientModel()
end
end)
end
end
function SWEP:CanBePickedUpByNPCs()
return true
end
hook.Add("PlayerCanPickupWeapon", "NPCWeaponsDisallowPlayerPickup", function(ply, wep)
if wep.IsNPCWeapon then return false end
end) | f0e9b318c70009115ee8225c526bffbe65ea2a2f | [
"Markdown",
"Lua"
] | 9 | Lua | oliviercm/npcweaponsbase | 3df712a7a6f2f463fe68d267ee3e405e435287e7 | ef0bdb476bb7c0230cf47ef17cadc75942b533b9 | |
refs/heads/master | <repo_name>shiddiki/Trying-to-copy-CSharp<file_sep>/Form1.cs
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.Diagnostics;
using System.Threading;
namespace copeytry_direct
{
public partial class Form1 : Form
{
public static string[] fromnames;
public static string tonames;
public static string names11, names21 = "",names12,names22="",fromcopy1,fromcopy2;
public static int sent = 0,failedno = 0;
public static string[] failed;
static Thread tocpy1,tocpy2;
public Form1()
{
InitializeComponent();
}
string a;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog from = new OpenFileDialog();
from.Multiselect = true;
if (from.ShowDialog() == DialogResult.OK)
{
fromnames= from.FileNames;
//MessageBox.Show(fromnames);
}
}
private void button2_Click(object sender, EventArgs e)
{
FolderBrowserDialog to = new FolderBrowserDialog();
//to.m = true;
if (to.ShowDialog() == DialogResult.OK)
{
tonames = to.SelectedPath;
//MessageBox.Show(fromnames);
// copy();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
foreach (string fim in fromnames)
{
names11 = "";
names21 = "";
for (int i = fim.Length - 1; i >= 0; i--)
{
if (fim[i] == '\\')
break;
names11 += fim[i];
}
for (int i = names11.Length - 1; i >= 0; i--)
names21 += names11[i];
using (FileStream stream = File.OpenRead(fim))
Copystream(stream,tonames+"\\"+names21);
}
stopwatch.Stop();
MessageBox.Show("Time elapsed: " + stopwatch.Elapsed);
}
Environment.Exit(0);
}
public static void Copystream(System.IO.Stream inStream, string outputFilePath)
{
int bufferSize = 1024 * 1024;
/* using (inStream)
{
using (BinaryReader r = new BinaryReader(inStream))
{
using (FileStream fs = new FileStream(outputFilePath, FileMode.OpenOrCreate))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
w.Write(r.ReadBytes((int)inStream.Length - 1));
}
}
}
}*/
using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate,FileAccess.Write))
{
fileStream.SetLength(inStream.Length);
int bytesRead = -1;
byte[] bytes = new byte[bufferSize];
while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
{
fileStream.Write(bytes, 0, bytesRead);
fileStream.Flush();
}
}
}
private void copy()
{
Process[] processes = Process.GetProcesses();
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int tot = 0,faul=0;
string msg="";
foreach (string frompath in fromnames)
{
tot++;
if (tot!=0)
{
names11 = "";
names21 = "";
for (int i = frompath.Length - 1; i >= 0; i--)
{
if (frompath[i] == '\\')
break;
names11 += frompath[i];
}
for (int i = names11.Length - 1; i >= 0; i--)
names21 += names11[i];
fromcopy1 = "";
fromcopy1 = frompath;
tocpy1 = new Thread(thredcopy1);
tocpy1.Start();
}
else
{
names12 = "";
names22 = "";
for (int i = frompath.Length - 1; i >= 0; i--)
{
if (frompath[i] == '\\')
break;
names12 += frompath[i];
}
for (int i = names12.Length - 1; i >= 0; i--)
names22 += names12[i];
fromcopy2 = "";
fromcopy2 = frompath;
tocpy2 = new Thread(thredcopy2);
tocpy2.Start();
}
// if (tot == 0)
{
while (tot != sent)
{
faul++;
if (faul == 1000000)
faul = 0;
}
}
}
while (tot != sent)
{
faul++;
if (faul == 1000000)
faul = 0;
}
stopwatch.Stop();
if (failedno >= 1)
{
for (int i = 0; i < failedno; i++)
msg += failed[i] + "\\n";
MessageBox.Show(msg);
}
else
{
MessageBox.Show("Time elapsed: " + stopwatch.Elapsed);
}
}
public void thredcopy1()
{
string fm1 = fromcopy1;
// MessageBox.Show(fm1);
try
{
File.Copy(fm1, tonames + "\\" + names21);
}
catch(Exception es)
{
// MessageBox.Show(es.ToString());
failed[failedno] = "To copy file Form " + fm1 + " To" + tonames;
failedno++;
}
sent++;
tocpy1.Abort();
}
public void thredcopy2()
{
string fm2 = fromcopy2;
// MessageBox.Show(fm2);
try
{
File.Copy(fm2, tonames + "\\" + names22);
}
catch (Exception es)
{
// MessageBox.Show(es.ToString());
failed[failedno] = "To copy file Form " + fm2 + " To" + tonames;
failedno++;
}
sent++;
tocpy2.Abort();
}
}
}
<file_sep>/README.md
# Trying-to-copy-CSharp
Simply tried to copy files using different ways.
| 0ac43d32eb12ba23a231725ce18282f8d2a99414 | [
"Markdown",
"C#"
] | 2 | C# | shiddiki/Trying-to-copy-CSharp | 03b687b5632cc499fd29a0a8481d83801afa77c9 | dc8a7650cf114bd270f353c9f6c24eb30a5b2df9 | |
refs/heads/master | <repo_name>Checkmate50/slang<file_sep>/tools/render-test/shader-renderer-util.h
// shader-renderer-util.h
#pragma once
#include "render.h"
#include "shader-input-layout.h"
namespace renderer_test {
using namespace Slang;
struct BindingStateImpl : public Slang::RefObject
{
/// A register set consists of one or more contiguous indices.
/// To be valid index >= 0 and size >= 1
struct RegisterRange
{
/// True if contains valid contents
bool isValid() const { return size > 0; }
/// True if valid single value
bool isSingle() const { return size == 1; }
/// Get as a single index (must be at least one index)
int getSingleIndex() const { return (size == 1) ? index : -1; }
/// Return the first index
int getFirstIndex() const { return (size > 0) ? index : -1; }
/// True if contains register index
bool hasRegister(int registerIndex) const { return registerIndex >= index && registerIndex < index + size; }
static RegisterRange makeInvalid() { return RegisterRange{ -1, 0 }; }
static RegisterRange makeSingle(int index) { return RegisterRange{ int16_t(index), 1 }; }
static RegisterRange makeRange(int index, int size) { return RegisterRange{ int16_t(index), uint16_t(size) }; }
int16_t index; ///< The base index
uint16_t size; ///< The amount of register indices
};
void apply(IRenderer* renderer, PipelineType pipelineType);
struct OutputBinding
{
ComPtr<IResource> resource;
Slang::UInt entryIndex;
};
List<OutputBinding> outputBindings;
ComPtr<IPipelineLayout> pipelineLayout;
ComPtr<IDescriptorSet> descriptorSet;
int m_numRenderTargets = 1;
};
ComPtr<ISamplerState> _createSamplerState(
IRenderer* renderer,
const InputSamplerDesc& srcDesc);
/// Utility class containing functions that construct items on the renderer using the ShaderInputLayout representation
struct ShaderRendererUtil
{
/// Generate a texture using the InputTextureDesc and construct a TextureResource using the Renderer with the contents
static Slang::Result generateTextureResource(const InputTextureDesc& inputDesc, int bindFlags, IRenderer* renderer, ComPtr<ITextureResource>& textureOut);
/// Create texture resource using inputDesc, and texData to describe format, and contents
static Slang::Result createTextureResource(
const InputTextureDesc& inputDesc,
const TextureData& texData,
int bindFlags,
IRenderer* renderer,
ComPtr<ITextureResource>& textureOut);
/// Create the BufferResource using the renderer from the contents of inputDesc
static Slang::Result createBufferResource(
const InputBufferDesc& inputDesc,
bool isOutput,
size_t bufferSize,
const void* initData,
IRenderer* renderer,
ComPtr<IBufferResource>& bufferOut);
/// Create BindingState::Desc from the contents of layout
static Slang::Result createBindingState(
const ShaderInputLayout& layout,
IRenderer* renderer,
IBufferResource* addedConstantBuffer,
BindingStateImpl** outBindingState);
private:
/// Create BindingState::Desc from a list of ShaderInputLayout entries
static Slang::Result _createBindingState(
ShaderInputLayoutEntry* srcEntries,
int numEntries,
IRenderer* renderer,
IBufferResource* addedConstantBuffer,
BindingStateImpl** outBindingState);
};
} // renderer_test
<file_sep>/tools/gfx/renderer-shared.h
#pragma once
#include "tools/gfx/render.h"
#include "slang-context.h"
#include "core/slang-basic.h"
namespace gfx
{
struct GfxGUID
{
static const Slang::Guid IID_ISlangUnknown;
static const Slang::Guid IID_IDescriptorSetLayout;
static const Slang::Guid IID_IDescriptorSet;
static const Slang::Guid IID_IShaderProgram;
static const Slang::Guid IID_IPipelineLayout;
static const Slang::Guid IID_IPipelineState;
static const Slang::Guid IID_IResourceView;
static const Slang::Guid IID_ISamplerState;
static const Slang::Guid IID_IResource;
static const Slang::Guid IID_IBufferResource;
static const Slang::Guid IID_ITextureResource;
static const Slang::Guid IID_IInputLayout;
static const Slang::Guid IID_IRenderer;
static const Slang::Guid IID_IShaderObjectLayout;
static const Slang::Guid IID_IShaderObject;
};
gfx::StageType translateStage(SlangStage slangStage);
class Resource : public Slang::RefObject
{
public:
/// Get the type
SLANG_FORCE_INLINE IResource::Type getType() const { return m_type; }
/// True if it's a texture derived type
SLANG_FORCE_INLINE bool isTexture() const { return int(m_type) >= int(IResource::Type::Texture1D); }
/// True if it's a buffer derived type
SLANG_FORCE_INLINE bool isBuffer() const { return m_type == IResource::Type::Buffer; }
protected:
Resource(IResource::Type type)
: m_type(type)
{}
IResource::Type m_type;
};
class BufferResource : public IBufferResource, public Resource
{
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
IResource* getInterface(const Slang::Guid& guid);
public:
typedef Resource Parent;
/// Ctor
BufferResource(const Desc& desc)
: Parent(Type::Buffer)
, m_desc(desc)
{}
virtual SLANG_NO_THROW IResource::Type SLANG_MCALL getType() SLANG_OVERRIDE;
virtual SLANG_NO_THROW IBufferResource::Desc* SLANG_MCALL getDesc() SLANG_OVERRIDE;
protected:
Desc m_desc;
};
class TextureResource : public ITextureResource, public Resource
{
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
IResource* getInterface(const Slang::Guid& guid);
public:
typedef Resource Parent;
/// Ctor
TextureResource(const Desc& desc)
: Parent(desc.type)
, m_desc(desc)
{}
virtual SLANG_NO_THROW IResource::Type SLANG_MCALL getType() SLANG_OVERRIDE;
virtual SLANG_NO_THROW ITextureResource::Desc* SLANG_MCALL getDesc() SLANG_OVERRIDE;
protected:
Desc m_desc;
};
Result createProgramFromSlang(IRenderer* renderer, IShaderProgram::Desc const& desc, IShaderProgram** outProgram);
class RendererBase;
typedef uint32_t ShaderComponentID;
const ShaderComponentID kInvalidComponentID = 0xFFFFFFFF;
struct ExtendedShaderObjectType
{
slang::TypeReflection* slangType;
ShaderComponentID componentID;
};
struct ExtendedShaderObjectTypeList
{
Slang::ShortList<ShaderComponentID, 16> componentIDs;
Slang::ShortList<slang::SpecializationArg, 16> components;
void add(const ExtendedShaderObjectType& component)
{
componentIDs.add(component.componentID);
components.add(slang::SpecializationArg{ slang::SpecializationArg::Kind::Type, component.slangType });
}
ExtendedShaderObjectType operator[](Slang::Index index) const
{
ExtendedShaderObjectType result;
result.componentID = componentIDs[index];
result.slangType = components[index].type;
return result;
}
void clear()
{
componentIDs.clear();
components.clear();
}
Slang::Index getCount()
{
return componentIDs.getCount();
}
};
class ShaderObjectLayoutBase : public IShaderObjectLayout, public Slang::RefObject
{
protected:
RendererBase* m_renderer;
slang::TypeLayoutReflection* m_elementTypeLayout = nullptr;
ShaderComponentID m_componentID = 0;
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
IShaderObjectLayout* getInterface(const Slang::Guid& guid);
RendererBase* getRenderer() { return m_renderer; }
slang::TypeLayoutReflection* getElementTypeLayout()
{
return m_elementTypeLayout;
}
ShaderComponentID getComponentID()
{
return m_componentID;
}
void initBase(RendererBase* renderer, slang::TypeLayoutReflection* elementTypeLayout);
};
class ShaderObjectBase : public IShaderObject, public Slang::RefObject
{
protected:
// The shader object layout used to create this shader object.
Slang::RefPtr<ShaderObjectLayoutBase> m_layout = nullptr;
// The specialized shader object type.
ExtendedShaderObjectType shaderObjectType = { nullptr, kInvalidComponentID };
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
IShaderObject* getInterface(const Slang::Guid& guid);
public:
ShaderComponentID getComponentID()
{
return shaderObjectType.componentID;
}
// Get the final type this shader object represents. If the shader object's type has existential fields,
// this function will return a specialized type using the bound sub-objects' type as specialization argument.
Result getSpecializedShaderObjectType(ExtendedShaderObjectType* outType);
RendererBase* getRenderer() { return m_layout->getRenderer(); }
SLANG_NO_THROW UInt SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return 0; }
SLANG_NO_THROW Result SLANG_MCALL getEntryPoint(UInt index, IShaderObject** outEntryPoint)
SLANG_OVERRIDE
{
*outEntryPoint = nullptr;
return SLANG_OK;
}
ShaderObjectLayoutBase* getLayout()
{
return m_layout;
}
SLANG_NO_THROW slang::TypeLayoutReflection* SLANG_MCALL getElementTypeLayout() SLANG_OVERRIDE
{
return m_layout->getElementTypeLayout();
}
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) = 0;
};
class ShaderProgramBase : public IShaderProgram, public Slang::RefObject
{
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
IShaderProgram* getInterface(const Slang::Guid& guid);
ComPtr<slang::IComponentType> slangProgram;
};
class PipelineStateBase : public IPipelineState, public Slang::RefObject
{
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
IPipelineState* getInterface(const Slang::Guid& guid);
struct PipelineStateDesc
{
PipelineType type;
GraphicsPipelineStateDesc graphics;
ComputePipelineStateDesc compute;
ShaderProgramBase* getProgram()
{
return static_cast<ShaderProgramBase*>(type == PipelineType::Compute ? compute.program : graphics.program);
}
} desc;
// The pipeline state from which this pipeline state is specialized.
// If null, this pipeline is either an unspecialized pipeline.
Slang::RefPtr<PipelineStateBase> unspecializedPipelineState = nullptr;
// Indicates whether this is a specializable pipeline. A specializable
// pipeline cannot be used directly and must be specialized first.
bool isSpecializable = false;
protected:
void initializeBase(const PipelineStateDesc& inDesc);
};
class ShaderBinary : public Slang::RefObject
{
public:
Slang::List<uint8_t> source;
StageType stage;
Slang::String entryPointName;
Result loadFromBlob(ISlangBlob* blob);
Result writeToBlob(ISlangBlob** outBlob);
};
struct ComponentKey
{
Slang::UnownedStringSlice typeName;
Slang::ShortList<ShaderComponentID> specializationArgs;
Slang::HashCode hash;
Slang::HashCode getHashCode()
{
return hash;
}
void updateHash()
{
hash = typeName.getHashCode();
for (auto& arg : specializationArgs)
hash = Slang::combineHash(hash, arg);
}
};
struct PipelineKey
{
PipelineStateBase* pipeline;
Slang::ShortList<ShaderComponentID> specializationArgs;
Slang::HashCode hash;
Slang::HashCode getHashCode()
{
return hash;
}
void updateHash()
{
hash = Slang::getHashCode(pipeline);
for (auto& arg : specializationArgs)
hash = Slang::combineHash(hash, arg);
}
bool operator==(const PipelineKey& other)
{
if (pipeline != other.pipeline)
return false;
if (specializationArgs.getCount() != other.specializationArgs.getCount())
return false;
for (Slang::Index i = 0; i < other.specializationArgs.getCount(); i++)
{
if (specializationArgs[i] != other.specializationArgs[i])
return false;
}
return true;
}
};
struct OwningComponentKey
{
Slang::String typeName;
Slang::ShortList<ShaderComponentID> specializationArgs;
Slang::HashCode hash;
Slang::HashCode getHashCode()
{
return hash;
}
template<typename KeyType>
bool operator==(const KeyType& other)
{
if (typeName != other.typeName)
return false;
if (specializationArgs.getCount() != other.specializationArgs.getCount())
return false;
for (Slang::Index i = 0; i < other.specializationArgs.getCount(); i++)
{
if (specializationArgs[i] != other.specializationArgs[i])
return false;
}
return true;
}
};
// A cache from specialization keys to a specialized `ShaderKernel`.
class ShaderCache : public Slang::RefObject
{
public:
ShaderComponentID getComponentId(slang::TypeReflection* type);
ShaderComponentID getComponentId(Slang::UnownedStringSlice name);
ShaderComponentID getComponentId(ComponentKey key);
void init(ISlangFileSystem* cacheFileSystem);
void writeToFileSystem(ISlangMutableFileSystem* outputFileSystem);
Slang::ComPtr<IPipelineState> getSpecializedPipelineState(PipelineKey programKey)
{
Slang::ComPtr<IPipelineState> result;
if (specializedPipelines.TryGetValue(programKey, result))
return result;
return nullptr;
}
Slang::RefPtr<ShaderBinary> tryLoadShaderBinary(ShaderComponentID componentId);
void addShaderBinary(ShaderComponentID componentId, ShaderBinary* binary);
void addSpecializedPipeline(PipelineKey key, Slang::ComPtr<IPipelineState> specializedPipeline);
protected:
Slang::ComPtr<ISlangFileSystem> fileSystem;
Slang::OrderedDictionary<OwningComponentKey, ShaderComponentID> componentIds;
Slang::OrderedDictionary<PipelineKey, Slang::ComPtr<IPipelineState>> specializedPipelines;
Slang::OrderedDictionary<ShaderComponentID, Slang::RefPtr<ShaderBinary>> shaderBinaries;
};
// Renderer implementation shared by all platforms.
// Responsible for shader compilation, specialization and caching.
class RendererBase : public Slang::RefObject, public IRenderer
{
public:
SLANG_REF_OBJECT_IUNKNOWN_ALL
virtual SLANG_NO_THROW Result SLANG_MCALL getFeatures(
const char** outFeatures, UInt bufferSize, UInt* outFeatureCount) SLANG_OVERRIDE;
virtual SLANG_NO_THROW bool SLANG_MCALL hasFeature(const char* featureName) SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL getSlangSession(slang::ISession** outSlangSession) SLANG_OVERRIDE;
IRenderer* getInterface(const Slang::Guid& guid);
protected:
// Retrieves the currently bound unspecialized pipeline.
// If the bound pipeline is not created from a Slang component, an implementation should return null.
virtual PipelineStateBase* getCurrentPipeline() = 0;
ExtendedShaderObjectTypeList specializationArgs;
// Given current pipeline and root shader object binding, generate and bind a specialized pipeline if necessary.
Result maybeSpecializePipeline(ShaderObjectBase* inRootShaderObject);
protected:
virtual SLANG_NO_THROW SlangResult SLANG_MCALL initialize(const Desc& desc, void* inWindowHandle);
protected:
Slang::List<Slang::String> m_features;
public:
SlangContext slangContext;
ShaderCache shaderCache;
};
}
<file_sep>/tools/gfx/render-graphics-common.cpp
#include "render-graphics-common.h"
#include "core/slang-basic.h"
using namespace Slang;
namespace gfx
{
class GraphicsCommonShaderObjectLayout : public ShaderObjectLayoutBase
{
public:
struct BindingRangeInfo
{
slang::BindingType bindingType;
Index count;
Index baseIndex;
Index descriptorSetIndex;
Index rangeIndexInDescriptorSet;
// Returns true if this binding range consumes a specialization argument slot.
bool isSpecializationArg() const
{
return bindingType == slang::BindingType::ExistentialValue;
}
};
struct SubObjectRangeInfo
{
ComPtr<GraphicsCommonShaderObjectLayout> layout;
// Index baseIndex;
// Index count;
Index bindingRangeIndex;
};
struct DescriptorSetInfo : public RefObject
{
ComPtr<IDescriptorSetLayout> layout;
Slang::Int space = -1;
};
struct Builder
{
public:
Builder(RendererBase* renderer)
: m_renderer(renderer)
{}
RendererBase* m_renderer;
slang::TypeLayoutReflection* m_elementTypeLayout;
List<BindingRangeInfo> m_bindingRanges;
List<SubObjectRangeInfo> m_subObjectRanges;
Index m_resourceViewCount = 0;
Index m_samplerCount = 0;
Index m_combinedTextureSamplerCount = 0;
Index m_subObjectCount = 0;
Index m_varyingInputCount = 0;
Index m_varyingOutputCount = 0;
struct DescriptorSetBuildInfo : public RefObject
{
List<IDescriptorSetLayout::SlotRangeDesc> slotRangeDescs;
Index space;
};
List<RefPtr<DescriptorSetBuildInfo>> m_descriptorSetBuildInfos;
Dictionary<Index, Index> m_mapSpaceToDescriptorSetIndex;
Index findOrAddDescriptorSet(Index space)
{
Index index;
if (m_mapSpaceToDescriptorSetIndex.TryGetValue(space, index))
return index;
RefPtr<DescriptorSetBuildInfo> info = new DescriptorSetBuildInfo();
info->space = space;
index = m_descriptorSetBuildInfos.getCount();
m_descriptorSetBuildInfos.add(info);
m_mapSpaceToDescriptorSetIndex.Add(space, index);
return index;
}
static DescriptorSlotType _mapDescriptorType(slang::BindingType slangBindingType)
{
switch (slangBindingType)
{
default:
return DescriptorSlotType::Unknown;
#define CASE(FROM, TO) \
case slang::BindingType::FROM: \
return DescriptorSlotType::TO
CASE(Sampler, Sampler);
CASE(CombinedTextureSampler, CombinedImageSampler);
CASE(Texture, SampledImage);
CASE(MutableTexture, StorageImage);
CASE(TypedBuffer, UniformTexelBuffer);
CASE(MutableTypedBuffer, StorageTexelBuffer);
CASE(RawBuffer, ReadOnlyStorageBuffer);
CASE(MutableRawBuffer, StorageBuffer);
CASE(InputRenderTarget, InputAttachment);
CASE(InlineUniformData, InlineUniformBlock);
CASE(RayTracingAccelerationStructure, RayTracingAccelerationStructure);
CASE(ConstantBuffer, UniformBuffer);
CASE(PushConstant, RootConstant);
#undef CASE
}
}
slang::TypeLayoutReflection* unwrapParameterGroups(slang::TypeLayoutReflection* typeLayout)
{
for (;;)
{
if (!typeLayout->getType())
{
if (auto elementTypeLayout = typeLayout->getElementTypeLayout())
typeLayout = elementTypeLayout;
}
switch (typeLayout->getKind())
{
default:
return typeLayout;
case slang::TypeReflection::Kind::ConstantBuffer:
case slang::TypeReflection::Kind::ParameterBlock:
typeLayout = typeLayout->getElementTypeLayout();
continue;
}
}
}
void _addDescriptorSets(
slang::TypeLayoutReflection* typeLayout,
slang::VariableLayoutReflection* varLayout = nullptr)
{
SlangInt descriptorSetCount = typeLayout->getDescriptorSetCount();
for (SlangInt s = 0; s < descriptorSetCount; ++s)
{
auto descriptorSetIndex =
findOrAddDescriptorSet(typeLayout->getDescriptorSetSpaceOffset(s));
auto descriptorSetInfo = m_descriptorSetBuildInfos[descriptorSetIndex];
SlangInt descriptorRangeCount = typeLayout->getDescriptorSetDescriptorRangeCount(s);
for (SlangInt r = 0; r < descriptorRangeCount; ++r)
{
auto slangBindingType = typeLayout->getDescriptorSetDescriptorRangeType(s, r);
switch (slangBindingType)
{
case slang::BindingType::ExistentialValue:
case slang::BindingType::InlineUniformData:
continue;
default:
break;
}
auto gfxDescriptorType = _mapDescriptorType(slangBindingType);
IDescriptorSetLayout::SlotRangeDesc descriptorRangeDesc;
descriptorRangeDesc.binding =
typeLayout->getDescriptorSetDescriptorRangeIndexOffset(s, r);
descriptorRangeDesc.count =
typeLayout->getDescriptorSetDescriptorRangeDescriptorCount(s, r);
descriptorRangeDesc.type = gfxDescriptorType;
if (varLayout)
{
auto category = typeLayout->getDescriptorSetDescriptorRangeCategory(s, r);
descriptorRangeDesc.binding += varLayout->getOffset(category);
}
descriptorSetInfo->slotRangeDescs.add(descriptorRangeDesc);
}
}
}
Result setElementTypeLayout(slang::TypeLayoutReflection* typeLayout)
{
typeLayout = unwrapParameterGroups(typeLayout);
m_elementTypeLayout = typeLayout;
// First we will use the Slang layout information to allocate
// the descriptor set layout(s) required to store values
// of the given type.
//
_addDescriptorSets(typeLayout);
// Next we will compute the binding ranges that are used to store
// the logical contents of the object in memory. These will relate
// to the descriptor ranges in the various sets, but not always
// in a one-to-one fashion.
SlangInt bindingRangeCount = typeLayout->getBindingRangeCount();
for (SlangInt r = 0; r < bindingRangeCount; ++r)
{
slang::BindingType slangBindingType = typeLayout->getBindingRangeType(r);
SlangInt count = typeLayout->getBindingRangeBindingCount(r);
slang::TypeLayoutReflection* slangLeafTypeLayout =
typeLayout->getBindingRangeLeafTypeLayout(r);
SlangInt descriptorSetIndex = typeLayout->getBindingRangeDescriptorSetIndex(r);
SlangInt rangeIndexInDescriptorSet =
typeLayout->getBindingRangeFirstDescriptorRangeIndex(r);
Index baseIndex = 0;
switch (slangBindingType)
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
case slang::BindingType::ExistentialValue:
baseIndex = m_subObjectCount;
m_subObjectCount += count;
break;
case slang::BindingType::Sampler:
baseIndex = m_samplerCount;
m_samplerCount += count;
break;
case slang::BindingType::CombinedTextureSampler:
baseIndex = m_combinedTextureSamplerCount;
m_combinedTextureSamplerCount += count;
break;
case slang::BindingType::VaryingInput:
baseIndex = m_varyingInputCount;
m_varyingInputCount += count;
break;
case slang::BindingType::VaryingOutput:
baseIndex = m_varyingOutputCount;
m_varyingOutputCount += count;
break;
default:
baseIndex = m_resourceViewCount;
m_resourceViewCount += count;
break;
}
BindingRangeInfo bindingRangeInfo;
bindingRangeInfo.bindingType = slangBindingType;
bindingRangeInfo.count = count;
bindingRangeInfo.baseIndex = baseIndex;
bindingRangeInfo.descriptorSetIndex = descriptorSetIndex;
bindingRangeInfo.rangeIndexInDescriptorSet = rangeIndexInDescriptorSet;
m_bindingRanges.add(bindingRangeInfo);
#if 0
SlangInt binding = typeLayout->getBindingRangeIndexOffset(r);
SlangInt space = typeLayout->getBindingRangeSpaceOffset(r);
SlangInt subObjectRangeIndex = typeLayout->getBindingRangeSubObjectRangeIndex(r);
DescriptorSetLayout::SlotRangeDesc slotRange;
slotRange.type = _mapDescriptorType(slangBindingType);
slotRange.count = count;
slotRange.binding = binding;
Index descriptorSetIndex = findOrAddDescriptorSet(space);
RefPtr<DescriptorSetBuildInfo> descriptorSetInfo = m_descriptorSetInfos[descriptorSetIndex];
Index slotRangeIndex = descriptorSetInfo->slotRanges.getCount();
descriptorSetInfo->slotRanges.add(slotRange);
#endif
}
SlangInt subObjectRangeCount = typeLayout->getSubObjectRangeCount();
for (SlangInt r = 0; r < subObjectRangeCount; ++r)
{
SlangInt bindingRangeIndex = typeLayout->getSubObjectRangeBindingRangeIndex(r);
auto slangBindingType = typeLayout->getBindingRangeType(bindingRangeIndex);
slang::TypeLayoutReflection* slangLeafTypeLayout =
typeLayout->getBindingRangeLeafTypeLayout(bindingRangeIndex);
// A sub-object range can either represent a sub-object of a known
// type, like a `ConstantBuffer<Foo>` or `ParameterBlock<Foo>`
// (in which case we can pre-compute a layout to use, based on
// the type `Foo`) *or* it can represent a sub-object of some
// existential type (e.g., `IBar`) in which case we cannot
// know the appropraite type/layout of sub-object to allocate.
//
RefPtr<GraphicsCommonShaderObjectLayout> subObjectLayout;
if (slangBindingType != slang::BindingType::ExistentialValue)
{
GraphicsCommonShaderObjectLayout::createForElementType(
m_renderer,
slangLeafTypeLayout->getElementTypeLayout(),
subObjectLayout.writeRef());
}
SubObjectRangeInfo subObjectRange;
subObjectRange.bindingRangeIndex = bindingRangeIndex;
subObjectRange.layout = subObjectLayout;
m_subObjectRanges.add(subObjectRange);
}
#if 0
SlangInt subObjectRangeCount = typeLayout->getSubObjectRangeCount();
for(SlangInt r = 0; r < subObjectRangeCount; ++r)
{
// TODO: Still need a way to map the binding ranges for
// the sub-object over so that they can be used to
// set/get the sub-object as needed.
}
#endif
return SLANG_OK;
}
SlangResult build(GraphicsCommonShaderObjectLayout** outLayout)
{
auto layout =
ComPtr<GraphicsCommonShaderObjectLayout>(new GraphicsCommonShaderObjectLayout());
SLANG_RETURN_ON_FAIL(layout->_init(this));
*outLayout = layout.detach();
return SLANG_OK;
}
};
static Result createForElementType(
RendererBase* renderer,
slang::TypeLayoutReflection* elementType,
GraphicsCommonShaderObjectLayout** outLayout)
{
Builder builder(renderer);
builder.setElementTypeLayout(elementType);
return builder.build(outLayout);
}
List<RefPtr<DescriptorSetInfo>> const& getDescriptorSets() { return m_descriptorSets; }
List<BindingRangeInfo> const& getBindingRanges() { return m_bindingRanges; }
Index getBindingRangeCount() { return m_bindingRanges.getCount(); }
BindingRangeInfo const& getBindingRange(Index index) { return m_bindingRanges[index]; }
slang::TypeLayoutReflection* getElementTypeLayout() { return m_elementTypeLayout; }
Index getResourceViewCount() { return m_resourceViewCount; }
Index getSamplerCount() { return m_samplerCount; }
Index getCombinedTextureSamplerCount() { return m_combinedTextureSamplerCount; }
Index getSubObjectCount() { return m_subObjectCount; }
SubObjectRangeInfo const& getSubObjectRange(Index index) { return m_subObjectRanges[index]; }
List<SubObjectRangeInfo> const& getSubObjectRanges() { return m_subObjectRanges; }
RendererBase* getRenderer() { return m_renderer; }
slang::TypeReflection* getType()
{
return m_elementTypeLayout->getType();
}
protected:
Result _init(Builder const* builder)
{
auto renderer = builder->m_renderer;
initBase(renderer, builder->m_elementTypeLayout);
m_bindingRanges = builder->m_bindingRanges;
for (auto descriptorSetBuildInfo : builder->m_descriptorSetBuildInfos)
{
auto& slotRangeDescs = descriptorSetBuildInfo->slotRangeDescs;
IDescriptorSetLayout::Desc desc;
desc.slotRangeCount = slotRangeDescs.getCount();
desc.slotRanges = slotRangeDescs.getBuffer();
ComPtr<IDescriptorSetLayout> descriptorSetLayout;
SLANG_RETURN_ON_FAIL(
m_renderer->createDescriptorSetLayout(desc, descriptorSetLayout.writeRef()));
RefPtr<DescriptorSetInfo> descriptorSetInfo = new DescriptorSetInfo();
descriptorSetInfo->layout = descriptorSetLayout;
descriptorSetInfo->space = descriptorSetBuildInfo->space;
m_descriptorSets.add(descriptorSetInfo);
}
m_resourceViewCount = builder->m_resourceViewCount;
m_samplerCount = builder->m_samplerCount;
m_combinedTextureSamplerCount = builder->m_combinedTextureSamplerCount;
m_subObjectCount = builder->m_subObjectCount;
m_subObjectRanges = builder->m_subObjectRanges;
return SLANG_OK;
}
List<RefPtr<DescriptorSetInfo>> m_descriptorSets;
List<BindingRangeInfo> m_bindingRanges;
Index m_resourceViewCount = 0;
Index m_samplerCount = 0;
Index m_combinedTextureSamplerCount = 0;
Index m_subObjectCount = 0;
List<SubObjectRangeInfo> m_subObjectRanges;
};
class EntryPointLayout : public GraphicsCommonShaderObjectLayout
{
typedef GraphicsCommonShaderObjectLayout Super;
public:
struct VaryingInputInfo
{};
struct VaryingOutputInfo
{};
struct Builder : Super::Builder
{
Builder(IRenderer* renderer)
: Super::Builder(static_cast<RendererBase*>(renderer))
{}
Result build(EntryPointLayout** outLayout)
{
RefPtr<EntryPointLayout> layout = new EntryPointLayout();
SLANG_RETURN_ON_FAIL(layout->_init(this));
*outLayout = layout.detach();
return SLANG_OK;
}
void _addEntryPointParam(slang::VariableLayoutReflection* entryPointParam)
{
auto slangStage = entryPointParam->getStage();
auto typeLayout = entryPointParam->getTypeLayout();
SlangInt bindingRangeCount = typeLayout->getBindingRangeCount();
for (SlangInt r = 0; r < bindingRangeCount; ++r)
{
slang::BindingType slangBindingType = typeLayout->getBindingRangeType(r);
SlangInt count = typeLayout->getBindingRangeBindingCount(r);
switch (slangBindingType)
{
default:
break;
case slang::BindingType::VaryingInput:
{
VaryingInputInfo info;
m_varyingInputs.add(info);
}
break;
case slang::BindingType::VaryingOutput:
{
VaryingOutputInfo info;
m_varyingOutputs.add(info);
}
break;
}
}
}
void addEntryPointParams(slang::EntryPointLayout* entryPointLayout)
{
m_slangEntryPointLayout = entryPointLayout;
setElementTypeLayout(entryPointLayout->getTypeLayout());
m_stage = translateStage(entryPointLayout->getStage());
_addEntryPointParam(entryPointLayout->getVarLayout());
_addEntryPointParam(entryPointLayout->getResultVarLayout());
}
slang::EntryPointLayout* m_slangEntryPointLayout = nullptr;
gfx::StageType m_stage;
List<VaryingInputInfo> m_varyingInputs;
List<VaryingOutputInfo> m_varyingOutputs;
};
Result _init(Builder const* builder)
{
auto renderer = builder->m_renderer;
SLANG_RETURN_ON_FAIL(Super::_init(builder));
m_slangEntryPointLayout = builder->m_slangEntryPointLayout;
m_stage = builder->m_stage;
m_varyingInputs = builder->m_varyingInputs;
m_varyingOutputs = builder->m_varyingOutputs;
return SLANG_OK;
}
List<VaryingInputInfo> const& getVaryingInputs() { return m_varyingInputs; }
List<VaryingOutputInfo> const& getVaryingOutputs() { return m_varyingOutputs; }
gfx::StageType getStage() const { return m_stage; }
slang::EntryPointLayout* getSlangLayout() const { return m_slangEntryPointLayout; };
slang::EntryPointLayout* m_slangEntryPointLayout;
gfx::StageType m_stage;
List<VaryingInputInfo> m_varyingInputs;
List<VaryingOutputInfo> m_varyingOutputs;
};
class GraphicsCommonProgramLayout : public GraphicsCommonShaderObjectLayout
{
typedef GraphicsCommonShaderObjectLayout Super;
public:
struct EntryPointInfo
{
RefPtr<EntryPointLayout> layout;
Index rangeOffset;
};
struct Builder : Super::Builder
{
Builder(IRenderer* renderer)
: Super::Builder(static_cast<RendererBase*>(renderer))
{}
Result build(GraphicsCommonProgramLayout** outLayout)
{
RefPtr<GraphicsCommonProgramLayout> layout = new GraphicsCommonProgramLayout();
SLANG_RETURN_ON_FAIL(layout->_init(this));
*outLayout = layout.detach();
return SLANG_OK;
}
void addGlobalParams(slang::VariableLayoutReflection* globalsLayout)
{
setElementTypeLayout(globalsLayout->getTypeLayout());
}
void addEntryPoint(EntryPointLayout* entryPointLayout)
{
EntryPointInfo info;
info.layout = entryPointLayout;
if (m_descriptorSetBuildInfos.getCount())
{
info.rangeOffset = m_descriptorSetBuildInfos[0]->slotRangeDescs.getCount();
}
else
{
info.rangeOffset = 0;
}
auto slangEntryPointLayout = entryPointLayout->getSlangLayout();
_addDescriptorSets(
slangEntryPointLayout->getTypeLayout(), slangEntryPointLayout->getVarLayout());
m_entryPoints.add(info);
}
List<EntryPointInfo> m_entryPoints;
};
Slang::Int getRenderTargetCount() { return m_renderTargetCount; }
IPipelineLayout* getPipelineLayout() { return m_pipelineLayout; }
Index findEntryPointIndex(gfx::StageType stage)
{
auto entryPointCount = m_entryPoints.getCount();
for (Index i = 0; i < entryPointCount; ++i)
{
auto entryPoint = m_entryPoints[i];
if (entryPoint.layout->getStage() == stage)
return i;
}
return -1;
}
EntryPointInfo const& getEntryPoint(Index index) { return m_entryPoints[index]; }
List<EntryPointInfo> const& getEntryPoints() const { return m_entryPoints; }
protected:
Result _init(Builder const* builder)
{
auto renderer = builder->m_renderer;
SLANG_RETURN_ON_FAIL(Super::_init(builder));
m_entryPoints = builder->m_entryPoints;
List<IPipelineLayout::DescriptorSetDesc> pipelineDescriptorSets;
_addDescriptorSetsRec(this, pipelineDescriptorSets);
#if 0
_createInputLayout(builder);
#endif
auto fragmentEntryPointIndex = findEntryPointIndex(gfx::StageType::Fragment);
if (fragmentEntryPointIndex != -1)
{
auto fragmentEntryPoint = getEntryPoint(fragmentEntryPointIndex);
m_renderTargetCount = fragmentEntryPoint.layout->getVaryingOutputs().getCount();
}
IPipelineLayout::Desc pipelineLayoutDesc;
// HACK: we set `renderTargetCount` to zero here becasue otherwise the D3D12
// render back-end will adjust all UAV registers by this value to account
// for the `SV_Target<N>` outputs implicitly consuming `u<N>` registers for
// Shader Model 5.0.
//
// When using the shader object path, all registers are being set via Slang
// reflection information, and we do not need/want the automatic adjustment.
//
// TODO: Once we eliminate the non-shader-object path, this whole issue should
// be moot, because the `ProgramLayout` should own/be the pipeline layout anyway.
//
pipelineLayoutDesc.renderTargetCount = 0;
pipelineLayoutDesc.descriptorSetCount = pipelineDescriptorSets.getCount();
pipelineLayoutDesc.descriptorSets = pipelineDescriptorSets.getBuffer();
SLANG_RETURN_ON_FAIL(
renderer->createPipelineLayout(pipelineLayoutDesc, m_pipelineLayout.writeRef()));
return SLANG_OK;
}
static void _addDescriptorSetsRec(
GraphicsCommonShaderObjectLayout* layout,
List<IPipelineLayout::DescriptorSetDesc>& ioPipelineDescriptorSets)
{
for (auto descriptorSetInfo : layout->getDescriptorSets())
{
IPipelineLayout::DescriptorSetDesc pipelineDescriptorSet;
pipelineDescriptorSet.layout = descriptorSetInfo->layout;
pipelineDescriptorSet.space = descriptorSetInfo->space;
ioPipelineDescriptorSets.add(pipelineDescriptorSet);
}
// TODO: next we need to recurse into the "sub-objects" of `layout` and
// add their descriptor sets as well.
}
#if 0
Result _createInputLayout(Builder const* builder)
{
auto renderer = builder->m_renderer;
List<InputElementDesc> const& inputElements = builder->getInputElements();
SLANG_RETURN_ON_FAIL(renderer->createInputLayout(inputElements.getBuffer(), inputElements.getCount(), m_inputLayout.writeRef()));
return SLANG_OK;
}
#endif
List<EntryPointInfo> m_entryPoints;
gfx::UInt m_renderTargetCount = 0;
ComPtr<IPipelineLayout> m_pipelineLayout;
};
class GraphicsCommonShaderObject : public ShaderObjectBase
{
public:
static Result create(
IRenderer* renderer,
GraphicsCommonShaderObjectLayout* layout,
GraphicsCommonShaderObject** outShaderObject)
{
auto object = ComPtr<GraphicsCommonShaderObject>(new GraphicsCommonShaderObject());
SLANG_RETURN_ON_FAIL(object->init(renderer, layout));
*outShaderObject = object.detach();
return SLANG_OK;
}
RendererBase* getRenderer() { return m_layout->getRenderer(); }
SLANG_NO_THROW UInt SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return 0; }
SLANG_NO_THROW Result SLANG_MCALL getEntryPoint(UInt index, IShaderObject** outEntryPoint)
SLANG_OVERRIDE
{
*outEntryPoint = nullptr;
return SLANG_OK;
}
GraphicsCommonShaderObjectLayout* getLayout()
{
return static_cast<GraphicsCommonShaderObjectLayout*>(m_layout.Ptr());
}
SLANG_NO_THROW slang::TypeLayoutReflection* SLANG_MCALL getElementTypeLayout() SLANG_OVERRIDE
{
return m_layout->getElementTypeLayout();
}
SLANG_NO_THROW Result SLANG_MCALL
setData(ShaderOffset const& offset, void const* data, size_t size) SLANG_OVERRIDE
{
IRenderer* renderer = getRenderer();
char* dest = (char*)renderer->map(m_buffer, MapFlavor::HostWrite);
memcpy(dest + offset.uniformOffset, data, size);
renderer->unmap(m_buffer);
return SLANG_OK;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
setObject(ShaderOffset const& offset, IShaderObject* object)
SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
auto layout = getLayout();
if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
return SLANG_E_INVALID_ARG;
auto subObject = static_cast<GraphicsCommonShaderObject*>(object);
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
// TODO: Is this reasonable to store the base index directly in the binding range?
m_objects[bindingRange.baseIndex + offset.bindingArrayIndex] = subObject;
return SLANG_E_NOT_IMPLEMENTED;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
getObject(ShaderOffset const& offset, IShaderObject** outObject)
SLANG_OVERRIDE
{
SLANG_ASSERT(outObject);
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
auto layout = getLayout();
if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
auto object = m_objects[bindingRange.baseIndex + offset.bindingArrayIndex].Ptr();
object->addRef();
*outObject = object;
// auto& subObjectRange =
// m_layout->getSubObjectRange(bindingRange.subObjectRangeIndex); *outObject =
// m_objects[subObjectRange.baseIndex + offset.bindingArrayIndex];
return SLANG_OK;
#if 0
SLANG_ASSERT(bindingRange.descriptorSetIndex >= 0);
SLANG_ASSERT(bindingRange.descriptorSetIndex < m_descriptorSets.getCount());
auto& descriptorSet = m_descriptorSets[bindingRange.descriptorSetIndex];
descriptorSet->setConstantBuffer(bindingRange.rangeIndexInDescriptorSet, offset.bindingArrayIndex, buffer);
return SLANG_OK;
#endif
}
SLANG_NO_THROW Result SLANG_MCALL
setResource(ShaderOffset const& offset, IResourceView* resourceView) SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
auto layout = getLayout();
if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
m_resourceViews[bindingRange.baseIndex + offset.bindingArrayIndex] = resourceView;
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL setSampler(ShaderOffset const& offset, ISamplerState* sampler)
SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
auto layout = getLayout();
if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
m_samplers[bindingRange.baseIndex + offset.bindingArrayIndex] = sampler;
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) SLANG_OVERRIDE
{
if (offset.bindingRangeIndex < 0)
return SLANG_E_INVALID_ARG;
auto layout = getLayout();
if (offset.bindingRangeIndex >= layout->getBindingRangeCount())
return SLANG_E_INVALID_ARG;
auto& bindingRange = layout->getBindingRange(offset.bindingRangeIndex);
auto& slot = m_combinedTextureSamplers[bindingRange.baseIndex + offset.bindingArrayIndex];
slot.textureView = textureView;
slot.sampler = sampler;
return SLANG_OK;
}
public:
// Appends all types that are used to specialize the element type of this shader object in `args` list.
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override
{
auto& subObjectRanges = getLayout()->getSubObjectRanges();
// The following logic is built on the assumption that all fields that involve existential types (and
// therefore require specialization) will results in a sub-object range in the type layout.
// This allows us to simply scan the sub-object ranges to find out all specialization arguments.
for (Index subObjIndex = 0; subObjIndex < subObjectRanges.getCount(); subObjIndex++)
{
// Retrieve the corresponding binding range of the sub object.
auto bindingRange = getLayout()->getBindingRange(subObjectRanges[subObjIndex].bindingRangeIndex);
switch (bindingRange.bindingType)
{
case slang::BindingType::ExistentialValue:
{
// A binding type of `ExistentialValue` means the sub-object represents a interface-typed field.
// In this case the specialization argument for this field is the actual specialized type of the bound
// shader object. If the shader object's type is an ordinary type without existential fields, then the
// type argument will simply be the ordinary type. But if the sub object's type is itself a specialized
// type, we need to make sure to use that type as the specialization argument.
// TODO: need to implement the case where the field is an array of existential values.
SLANG_ASSERT(bindingRange.count == 1);
ExtendedShaderObjectType specializedSubObjType;
SLANG_RETURN_ON_FAIL(m_objects[subObjIndex]->getSpecializedShaderObjectType(&specializedSubObjType));
args.add(specializedSubObjType);
break;
}
case slang::BindingType::ParameterBlock:
case slang::BindingType::ConstantBuffer:
// Currently we only handle the case where the field's type is
// `ParameterBlock<SomeStruct>` or `ConstantBuffer<SomeStruct>`, where `SomeStruct` is a struct type
// (not directly an interface type). In this case, we just recursively collect the specialization arguments
// from the bound sub object.
SLANG_RETURN_ON_FAIL(m_objects[subObjIndex]->collectSpecializationArgs(args));
// TODO: we need to handle the case where the field is of the form `ParameterBlock<IFoo>`. We should treat
// this case the same way as the `ExistentialValue` case here, but currently we lack a mechanism to distinguish
// the two scenarios.
break;
}
// TODO: need to handle another case where specialization happens on resources fields e.g. `StructuredBuffer<IFoo>`.
}
return SLANG_OK;
}
protected:
friend class ProgramVars;
Result init(IRenderer* renderer, GraphicsCommonShaderObjectLayout* layout)
{
m_layout = layout;
// If the layout tells us that there is any uniform data,
// then we need to allocate a constant buffer to hold that data.
//
// TODO: Do we need to allocate a shadow copy for use from
// the CPU?
//
// TODO: When/where do we bind this constant buffer into
// a descriptor set for later use?
//
size_t uniformSize = layout->getElementTypeLayout()->getSize();
if (uniformSize)
{
IBufferResource::Desc bufferDesc;
bufferDesc.init(uniformSize);
bufferDesc.cpuAccessFlags |= IResource::AccessFlag::Write;
SLANG_RETURN_ON_FAIL(renderer->createBufferResource(
IResource::Usage::ConstantBuffer, bufferDesc, nullptr, m_buffer.writeRef()));
}
#if 0
// If the layout tells us there are any descriptor sets to
// allocate, then we do so now.
//
for(auto descriptorSetInfo : layout->getDescriptorSets())
{
RefPtr<DescriptorSet> descriptorSet;
SLANG_RETURN_ON_FAIL(renderer->createDescriptorSet(descriptorSetInfo->layout, descriptorSet.writeRef()));
m_descriptorSets.add(descriptorSet);
}
#endif
m_resourceViews.setCount(layout->getResourceViewCount());
m_samplers.setCount(layout->getSamplerCount());
m_combinedTextureSamplers.setCount(layout->getCombinedTextureSamplerCount());
// If the layout specifies that we have any sub-objects, then
// we need to size the array to account for them.
//
Index subObjectCount = layout->getSubObjectCount();
m_objects.setCount(subObjectCount);
for (auto subObjectRangeInfo : layout->getSubObjectRanges())
{
auto subObjectLayout = subObjectRangeInfo.layout;
// In the case where the sub-object range represents an
// existential-type leaf field (e.g., an `IBar`), we
// cannot pre-allocate the object(s) to go into that
// range, since we can't possibly know what to allocate
// at this point.
//
if (!subObjectLayout)
continue;
//
// Otherwise, we will allocate a sub-object to fill
// in each entry in this range, based on the layout
// information we already have.
auto& bindingRangeInfo = layout->getBindingRange(subObjectRangeInfo.bindingRangeIndex);
for (Index i = 0; i < bindingRangeInfo.count; ++i)
{
RefPtr<GraphicsCommonShaderObject> subObject;
SLANG_RETURN_ON_FAIL(
GraphicsCommonShaderObject::create(renderer, subObjectLayout, subObject.writeRef()));
m_objects[bindingRangeInfo.baseIndex + i] = subObject;
}
}
return SLANG_OK;
}
Result apply(
IRenderer* renderer,
PipelineType pipelineType,
IPipelineLayout* pipelineLayout,
Index& ioRootIndex)
{
GraphicsCommonShaderObjectLayout* layout = getLayout();
// Create the descritpor sets required by the layout...
//
List<ComPtr<IDescriptorSet>> descriptorSets;
for (auto descriptorSetInfo : layout->getDescriptorSets())
{
ComPtr<IDescriptorSet> descriptorSet;
SLANG_RETURN_ON_FAIL(
renderer->createDescriptorSet(descriptorSetInfo->layout, descriptorSet.writeRef()));
descriptorSets.add(descriptorSet);
}
SLANG_RETURN_ON_FAIL(_bindIntoDescriptorSets(descriptorSets.getBuffer()));
for (auto descriptorSet : descriptorSets)
{
renderer->setDescriptorSet(pipelineType, pipelineLayout, ioRootIndex++, descriptorSet);
}
return SLANG_OK;
}
Result _bindIntoDescriptorSet(
IDescriptorSet* descriptorSet, Index baseRangeIndex, Index subObjectRangeArrayIndex)
{
GraphicsCommonShaderObjectLayout* layout = getLayout();
if (m_buffer)
{
descriptorSet->setConstantBuffer(baseRangeIndex, subObjectRangeArrayIndex, m_buffer);
baseRangeIndex++;
}
for (auto bindingRangeInfo : layout->getBindingRanges())
{
switch (bindingRangeInfo.bindingType)
{
case slang::BindingType::VaryingInput:
case slang::BindingType::VaryingOutput:
continue;
default:
break;
}
SLANG_ASSERT(bindingRangeInfo.descriptorSetIndex == 0);
auto count = bindingRangeInfo.count;
auto baseIndex = bindingRangeInfo.baseIndex;
auto descriptorRangeIndex = baseRangeIndex + bindingRangeInfo.rangeIndexInDescriptorSet;
auto descriptorArrayBaseIndex = subObjectRangeArrayIndex * count;
switch (bindingRangeInfo.bindingType)
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
break;
case slang::BindingType::ExistentialValue:
//
// TODO: If the existential value is one that "fits" into the storage available,
// then we should write its data directly into that area. Otherwise, we need
// to bind its content as "pending" data which will come after any other data
// beloning to the same set (that is, it's starting descriptorRangeIndex will
// need to be one after the number of ranges accounted for in the original type)
//
break;
case slang::BindingType::CombinedTextureSampler:
for (Index i = 0; i < count; ++i)
{
auto& slot = m_combinedTextureSamplers[baseIndex + i];
descriptorSet->setCombinedTextureSampler(
descriptorRangeIndex,
descriptorArrayBaseIndex + i,
slot.textureView,
slot.sampler);
}
break;
case slang::BindingType::Sampler:
for (Index i = 0; i < count; ++i)
{
descriptorSet->setSampler(
descriptorRangeIndex,
descriptorArrayBaseIndex + i,
m_samplers[baseIndex + i]);
}
break;
default:
for (Index i = 0; i < count; ++i)
{
descriptorSet->setResource(
descriptorRangeIndex,
descriptorArrayBaseIndex + i,
m_resourceViews[baseIndex + i]);
}
break;
}
}
return SLANG_OK;
}
public:
virtual Result _bindIntoDescriptorSets(ComPtr<IDescriptorSet>* descriptorSets)
{
GraphicsCommonShaderObjectLayout* layout = getLayout();
if (m_buffer)
{
// TODO: look up binding infor for default constant buffer...
descriptorSets[0]->setConstantBuffer(0, 0, m_buffer);
}
// Fill in the descriptor sets based on binding ranges
//
for (auto bindingRangeInfo : layout->getBindingRanges())
{
auto descriptorSet = descriptorSets[bindingRangeInfo.descriptorSetIndex];
auto rangeIndex = bindingRangeInfo.rangeIndexInDescriptorSet;
auto baseIndex = bindingRangeInfo.baseIndex;
auto count = bindingRangeInfo.count;
switch (bindingRangeInfo.bindingType)
{
case slang::BindingType::ConstantBuffer:
case slang::BindingType::ParameterBlock:
for (Index i = 0; i < count; ++i)
{
GraphicsCommonShaderObject* subObject = m_objects[baseIndex + i];
subObject->_bindIntoDescriptorSet(descriptorSet, rangeIndex, i);
}
break;
case slang::BindingType::CombinedTextureSampler:
for (Index i = 0; i < count; ++i)
{
auto& slot = m_combinedTextureSamplers[baseIndex + i];
descriptorSet->setCombinedTextureSampler(
rangeIndex, i, slot.textureView, slot.sampler);
}
break;
case slang::BindingType::Sampler:
for (Index i = 0; i < count; ++i)
{
descriptorSet->setSampler(rangeIndex, i, m_samplers[baseIndex + i]);
}
break;
case slang::BindingType::VaryingInput:
case slang::BindingType::VaryingOutput:
break;
case slang::BindingType::ExistentialValue:
// Here we are binding as if existential value is the same
// as a constant buffer or parameter block, which will lead
// to incorrect results...
for (Index i = 0; i < count; ++i)
{
GraphicsCommonShaderObject* subObject = m_objects[baseIndex + i];
subObject->_bindIntoDescriptorSet(descriptorSet, rangeIndex, i);
}
break;
default:
for (Index i = 0; i < count; ++i)
{
descriptorSet->setResource(rangeIndex, i, m_resourceViews[baseIndex + i]);
}
break;
}
}
return SLANG_OK;
}
ComPtr<IBufferResource> m_buffer;
List<ComPtr<IResourceView>> m_resourceViews;
List<ComPtr<ISamplerState>> m_samplers;
struct CombinedTextureSamplerSlot
{
ComPtr<IResourceView> textureView;
ComPtr<ISamplerState> sampler;
};
List<CombinedTextureSamplerSlot> m_combinedTextureSamplers;
// List<RefPtr<DescriptorSet>> m_descriptorSets;
List<RefPtr<GraphicsCommonShaderObject>> m_objects;
};
class EntryPointVars : public GraphicsCommonShaderObject
{
typedef GraphicsCommonShaderObject Super;
public:
static Result
create(IRenderer* renderer, EntryPointLayout* layout, EntryPointVars** outShaderObject)
{
RefPtr<EntryPointVars> object = new EntryPointVars();
SLANG_RETURN_ON_FAIL(object->init(renderer, layout));
*outShaderObject = object.detach();
return SLANG_OK;
}
EntryPointLayout* getLayout() { return static_cast<EntryPointLayout*>(m_layout.Ptr()); }
protected:
Result init(IRenderer* renderer, EntryPointLayout* layout)
{
SLANG_RETURN_ON_FAIL(Super::init(renderer, layout));
return SLANG_OK;
}
};
class ProgramVars : public GraphicsCommonShaderObject
{
typedef GraphicsCommonShaderObject Super;
public:
static Result create(IRenderer* renderer, GraphicsCommonProgramLayout* layout, ProgramVars** outShaderObject)
{
RefPtr<ProgramVars> object = new ProgramVars();
SLANG_RETURN_ON_FAIL(object->init(renderer, layout));
*outShaderObject = object.detach();
return SLANG_OK;
}
GraphicsCommonProgramLayout* getLayout() { return static_cast<GraphicsCommonProgramLayout*>(m_layout.Ptr()); }
void apply(IRenderer* renderer, PipelineType pipelineType)
{
auto pipelineLayout = getLayout()->getPipelineLayout();
Index rootIndex = 0;
GraphicsCommonShaderObject::apply(renderer, pipelineType, pipelineLayout, rootIndex);
#if 0
Index descriptorSetCount = m_descriptorSets.getCount();
for(Index descriptorSetIndex = 0; descriptorSetIndex < descriptorSetCount; ++descriptorSetIndex)
{
renderer->setDescriptorSet(
pipelineType,
pipelineLayout,
descriptorSetIndex,
m_descriptorSets[descriptorSetIndex]);
}
#endif
// TODO: We also need to bind any descriptor sets that are
// part of sub-objects of this object.
}
List<RefPtr<EntryPointVars>> const& getEntryPoints() const { return m_entryPoints; }
UInt SLANG_MCALL getEntryPointCount() SLANG_OVERRIDE { return (UInt)m_entryPoints.getCount(); }
SlangResult SLANG_MCALL getEntryPoint(UInt index, IShaderObject** outEntryPoint) SLANG_OVERRIDE
{
*outEntryPoint = m_entryPoints[index];
m_entryPoints[index]->addRef();
return SLANG_OK;
}
virtual Result collectSpecializationArgs(ExtendedShaderObjectTypeList& args) override
{
SLANG_RETURN_ON_FAIL(GraphicsCommonShaderObject::collectSpecializationArgs(args));
for (auto& entryPoint : m_entryPoints)
{
SLANG_RETURN_ON_FAIL(entryPoint->collectSpecializationArgs(args));
}
return SLANG_OK;
}
protected:
virtual Result _bindIntoDescriptorSets(ComPtr<IDescriptorSet>* descriptorSets) override
{
SLANG_RETURN_ON_FAIL(Super::_bindIntoDescriptorSets(descriptorSets));
auto entryPointCount = m_entryPoints.getCount();
for (Index i = 0; i < entryPointCount; ++i)
{
auto entryPoint = m_entryPoints[i];
auto& entryPointInfo = getLayout()->getEntryPoint(i);
SLANG_RETURN_ON_FAIL(entryPoint->_bindIntoDescriptorSet(
descriptorSets[0], entryPointInfo.rangeOffset, 0));
}
return SLANG_OK;
}
Result init(IRenderer* renderer, GraphicsCommonProgramLayout* layout)
{
SLANG_RETURN_ON_FAIL(Super::init(renderer, layout));
for (auto entryPointInfo : layout->getEntryPoints())
{
RefPtr<EntryPointVars> entryPoint;
SLANG_RETURN_ON_FAIL(
EntryPointVars::create(renderer, entryPointInfo.layout, entryPoint.writeRef()));
m_entryPoints.add(entryPoint);
}
return SLANG_OK;
}
List<RefPtr<EntryPointVars>> m_entryPoints;
};
Result SLANG_MCALL GraphicsAPIRenderer::createShaderObjectLayout(
slang::TypeLayoutReflection* typeLayout, IShaderObjectLayout** outLayout)
{
RefPtr<GraphicsCommonShaderObjectLayout> layout;
SLANG_RETURN_ON_FAIL(GraphicsCommonShaderObjectLayout::createForElementType(
this, typeLayout, layout.writeRef()));
*outLayout = layout.detach();
return SLANG_OK;
}
Result SLANG_MCALL
GraphicsAPIRenderer::createShaderObject(IShaderObjectLayout* layout, IShaderObject** outObject)
{
RefPtr<GraphicsCommonShaderObject> shaderObject;
SLANG_RETURN_ON_FAIL(GraphicsCommonShaderObject::create(this,
reinterpret_cast<GraphicsCommonShaderObjectLayout*>(layout), shaderObject.writeRef()));
*outObject = shaderObject.detach();
return SLANG_OK;
}
Result SLANG_MCALL GraphicsAPIRenderer::createRootShaderObject(
IShaderProgram* program,
IShaderObject** outObject)
{
auto commonProgram = dynamic_cast<GraphicsCommonShaderProgram*>(program);
RefPtr<ProgramVars> shaderObject;
SLANG_RETURN_ON_FAIL(ProgramVars::create(this,
commonProgram->getLayout(),
shaderObject.writeRef()));
*outObject = shaderObject.detach();
return SLANG_OK;
}
Result GraphicsAPIRenderer::initProgramCommon(
GraphicsCommonShaderProgram* program,
IShaderProgram::Desc const& desc)
{
auto slangProgram = desc.slangProgram;
if(!slangProgram)
return SLANG_OK;
auto slangReflection = slangProgram->getLayout(0);
if(!slangReflection)
return SLANG_FAIL;
RefPtr<GraphicsCommonProgramLayout> programLayout;
{
GraphicsCommonProgramLayout::Builder builder(this);
builder.addGlobalParams(slangReflection->getGlobalParamsVarLayout());
SlangInt entryPointCount = slangReflection->getEntryPointCount();
for (SlangInt e = 0; e < entryPointCount; ++e)
{
auto slangEntryPoint = slangReflection->getEntryPointByIndex(e);
EntryPointLayout::Builder entryPointBuilder(this);
entryPointBuilder.addEntryPointParams(slangEntryPoint);
RefPtr<EntryPointLayout> entryPointLayout;
SLANG_RETURN_ON_FAIL(entryPointBuilder.build(entryPointLayout.writeRef()));
builder.addEntryPoint(entryPointLayout);
}
SLANG_RETURN_ON_FAIL(builder.build(programLayout.writeRef()));
}
program->slangProgram = slangProgram;
program->m_layout = programLayout;
return SLANG_OK;
}
Result SLANG_MCALL
GraphicsAPIRenderer::bindRootShaderObject(PipelineType pipelineType, IShaderObject* object)
{
auto programVars = dynamic_cast<ProgramVars*>(object);
if (!programVars)
return SLANG_E_INVALID_HANDLE;
SLANG_RETURN_ON_FAIL(maybeSpecializePipeline(programVars));
// Apply shader parameter bindings.
programVars->apply(this, pipelineType);
return SLANG_OK;
}
GraphicsCommonProgramLayout* gfx::GraphicsCommonShaderProgram::getLayout() const
{
return static_cast<GraphicsCommonProgramLayout*>(m_layout.Ptr());
}
void GraphicsAPIRenderer::preparePipelineDesc(GraphicsPipelineStateDesc& desc)
{
if (!desc.pipelineLayout)
{
auto program = dynamic_cast<GraphicsCommonShaderProgram*>(desc.program);
auto rootLayout = program->getLayout();
desc.renderTargetCount = rootLayout->getRenderTargetCount();
desc.pipelineLayout = rootLayout->getPipelineLayout();
}
}
void GraphicsAPIRenderer::preparePipelineDesc(ComputePipelineStateDesc& desc)
{
if (!desc.pipelineLayout)
{
auto program = dynamic_cast<GraphicsCommonShaderProgram*>(desc.program);
auto rootLayout = program->getLayout();
desc.pipelineLayout = rootLayout->getPipelineLayout();
}
}
}
<file_sep>/tools/gfx/render.h
// render.h
#pragma once
#include <float.h>
#include <assert.h>
#include "slang.h"
#include "slang-com-ptr.h"
#include "slang-com-helper.h"
#if defined(SLANG_GFX_DYNAMIC)
# if defined(_MSC_VER)
# ifdef SLANG_GFX_DYNAMIC_EXPORT
# define SLANG_GFX_API SLANG_DLL_EXPORT
# else
# define SLANG_GFX_API __declspec(dllimport)
# endif
# else
// TODO: need to consider compiler capabilities
//# ifdef SLANG_DYNAMIC_EXPORT
# define SLANG_GFX_API SLANG_DLL_EXPORT
//# endif
# endif
#endif
#ifndef SLANG_GFX_API
# define SLANG_GFX_API
#endif
namespace gfx {
using Slang::ComPtr;
typedef SlangResult Result;
// Had to move here, because Options needs types defined here
typedef SlangInt Int;
typedef SlangUInt UInt;
// Declare opaque type
class IInputLayout: public ISlangUnknown
{
};
#define SLANG_UUID_IInputLayout \
{ \
0x45223711, 0xa84b, 0x455c, { 0xbe, 0xfa, 0x49, 0x37, 0x42, 0x1e, 0x8e, 0x2e } \
}
enum class PipelineType
{
Unknown,
Graphics,
Compute,
RayTracing,
CountOf,
};
enum class StageType
{
Unknown,
Vertex,
Hull,
Domain,
Geometry,
Fragment,
Compute,
RayGeneration,
Intersection,
AnyHit,
ClosestHit,
Miss,
Callable,
Amplification,
Mesh,
CountOf,
};
enum class RendererType
{
Unknown,
DirectX11,
DirectX12,
OpenGl,
Vulkan,
CPU,
CUDA,
CountOf,
};
enum class ProjectionStyle
{
Unknown,
OpenGl,
DirectX,
Vulkan,
CountOf,
};
/// The style of the binding
enum class BindingStyle
{
Unknown,
DirectX,
OpenGl,
Vulkan,
CPU,
CUDA,
CountOf,
};
class IShaderProgram: public ISlangUnknown
{
public:
struct KernelDesc
{
StageType stage;
void const* codeBegin;
void const* codeEnd;
char const* entryPointName;
UInt getCodeSize() const { return (char const*)codeEnd - (char const*)codeBegin; }
};
struct Desc
{
PipelineType pipelineType;
KernelDesc const* kernels;
Int kernelCount;
/// Use instead of `kernels`/`kernelCount` if loading a Slang program.
slang::IComponentType* slangProgram;
/// Find and return the kernel for `stage`, if present.
KernelDesc const* findKernel(StageType stage) const
{
for(Int ii = 0; ii < kernelCount; ++ii)
if(kernels[ii].stage == stage)
return &kernels[ii];
return nullptr;
}
};
};
#define SLANG_UUID_IShaderProgram \
{ \
0x9d32d0ad, 0x915c, 0x4ffd, { 0x91, 0xe2, 0x50, 0x85, 0x54, 0xa0, 0x4a, 0x76 } \
}
/// Different formats of things like pixels or elements of vertices
/// NOTE! Any change to this type (adding, removing, changing order) - must also be reflected in changes to RendererUtil
enum class Format
{
Unknown,
RGBA_Float32,
RGB_Float32,
RG_Float32,
R_Float32,
RGBA_Unorm_UInt8,
R_UInt16,
R_UInt32,
D_Float32,
D_Unorm24_S8,
CountOf,
};
struct InputElementDesc
{
char const* semanticName;
UInt semanticIndex;
Format format;
UInt offset;
};
enum class MapFlavor
{
Unknown, ///< Unknown mapping type
HostRead,
HostWrite,
WriteDiscard,
};
enum class PrimitiveTopology
{
TriangleList,
};
class IResource: public ISlangUnknown
{
public:
/// The type of resource.
/// NOTE! The order needs to be such that all texture types are at or after Texture1D (otherwise isTexture won't work correctly)
enum class Type
{
Unknown, ///< Unknown
Buffer, ///< A buffer (like a constant/index/vertex buffer)
Texture1D, ///< A 1d texture
Texture2D, ///< A 2d texture
Texture3D, ///< A 3d texture
TextureCube, ///< A cubemap consists of 6 Texture2D like faces
CountOf,
};
/// Describes how a resource is to be used
enum class Usage
{
Unknown = -1,
VertexBuffer = 0,
IndexBuffer,
ConstantBuffer,
StreamOutput,
RenderTarget,
DepthRead,
DepthWrite,
UnorderedAccess,
PixelShaderResource,
NonPixelShaderResource,
GenericRead,
CountOf,
};
/// Binding flags describe all of the ways a resource can be bound - and therefore used
struct BindFlag
{
enum Enum
{
VertexBuffer = 0x001,
IndexBuffer = 0x002,
ConstantBuffer = 0x004,
StreamOutput = 0x008,
RenderTarget = 0x010,
DepthStencil = 0x020,
UnorderedAccess = 0x040,
PixelShaderResource = 0x080,
NonPixelShaderResource = 0x100,
};
};
/// Combinations describe how a resource can be accessed (typically by the host/cpu)
struct AccessFlag
{
enum Enum
{
Read = 0x1,
Write = 0x2
};
};
/// Base class for Descs
struct DescBase
{
bool canBind(BindFlag::Enum bindFlag) const { return (bindFlags & bindFlag) != 0; }
bool hasCpuAccessFlag(AccessFlag::Enum accessFlag) { return (cpuAccessFlags & accessFlag) != 0; }
Type type = Type::Unknown;
int bindFlags = 0; ///< Combination of Resource::BindFlag or 0 (and will use initialUsage to set)
int cpuAccessFlags = 0; ///< Combination of Resource::AccessFlag
};
inline static BindFlag::Enum getDefaultBindFlagsFromUsage(IResource::Usage usage)
{
switch (usage)
{
case Usage::VertexBuffer:
return BindFlag::VertexBuffer;
case Usage::IndexBuffer:
return BindFlag::IndexBuffer;
case Usage::ConstantBuffer:
return BindFlag::ConstantBuffer;
case Usage::StreamOutput:
return BindFlag::StreamOutput;
case Usage::RenderTarget:
return BindFlag::RenderTarget;
case Usage::DepthRead:
case Usage::DepthWrite:
return BindFlag::DepthStencil;
case Usage::UnorderedAccess:
return BindFlag::Enum(BindFlag::UnorderedAccess | BindFlag::PixelShaderResource |
BindFlag::NonPixelShaderResource);
case Usage::PixelShaderResource:
return BindFlag::PixelShaderResource;
case Usage::NonPixelShaderResource:
return BindFlag::NonPixelShaderResource;
case Usage::GenericRead:
return BindFlag::Enum(
BindFlag::PixelShaderResource |
BindFlag::NonPixelShaderResource);
default:
return BindFlag::Enum(-1);
}
}
virtual SLANG_NO_THROW Type SLANG_MCALL getType() = 0;
};
#define SLANG_UUID_IResource \
{ \
0xa0e39f34, 0x8398, 0x4522, { 0x95, 0xc2, 0xeb, 0xc0, 0xf9, 0x84, 0xef, 0x3f } \
}
class IBufferResource: public IResource
{
public:
struct Desc: public DescBase
{
void init(size_t sizeInBytesIn)
{
sizeInBytes = sizeInBytesIn;
elementSize = 0;
format = Format::Unknown;
}
void setDefaults(Usage initialUsage)
{
if (bindFlags == 0)
{
bindFlags = getDefaultBindFlagsFromUsage(initialUsage);
}
}
size_t sizeInBytes; ///< Total size in bytes
int elementSize; ///< Get the element stride. If > 0, this is a structured buffer
Format format;
};
virtual SLANG_NO_THROW Desc* SLANG_MCALL getDesc() = 0;
};
#define SLANG_UUID_IBufferResource \
{ \
0x1b274efe, 0x5e37, 0x492b, { 0x82, 0x6e, 0x7e, 0xe7, 0xe8, 0xf5, 0xa4, 0x9b } \
}
template <typename T> T _slang_gfx_max(T v0, T v1) { return v0 > v1 ? v0 : v1; }
static inline unsigned int _slang_gfx_ones32(unsigned int x)
{
/* 32-bit recursive reduction using SWAR...
but first step is mapping 2-bit values
into sum of 2 1-bit values in sneaky way
*/
x -= ((x >> 1) & 0x55555555);
x = (((x >> 2) & 0x33333333) + (x & 0x33333333));
x = (((x >> 4) + x) & 0x0f0f0f0f);
x += (x >> 8);
x += (x >> 16);
return (x & 0x0000003f);
}
static inline unsigned int _slang_gfx_log2Floor(unsigned int x)
{
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
x |= (x >> 8);
x |= (x >> 16);
return (_slang_gfx_ones32(x >> 1));
}
class ITextureResource: public IResource
{
public:
struct SampleDesc
{
void init()
{
numSamples = 1;
quality = 0;
}
int numSamples; ///< Number of samples per pixel
int quality; ///< The quality measure for the samples
};
struct Size
{
void init()
{
width = height = depth = 1;
}
void init(int widthIn, int heightIn = 1, int depthIn = 1)
{
width = widthIn;
height = heightIn;
depth = depthIn;
}
/// Given the type works out the maximum dimension size
int calcMaxDimension(Type type) const
{
switch (type)
{
case IResource::Type::Texture1D:
return this->width;
case IResource::Type::Texture3D:
return _slang_gfx_max(_slang_gfx_max(this->width, this->height), this->depth);
case IResource::Type::TextureCube: // fallthru
case IResource::Type::Texture2D:
{
return _slang_gfx_max(this->width, this->height);
}
default:
return 0;
}
}
SLANG_FORCE_INLINE static int calcMipSize(int width, int mipLevel)
{
width = width >> mipLevel;
return width > 0 ? width : 1;
}
/// Given a size, calculates the size at a mip level
Size calcMipSize(int mipLevel) const
{
Size size;
size.width = calcMipSize(this->width, mipLevel);
size.height = calcMipSize(this->height, mipLevel);
size.depth = calcMipSize(this->depth, mipLevel);
return size;
}
int width; ///< Width in pixels
int height; ///< Height in pixels (if 2d or 3d)
int depth; ///< Depth (if 3d)
};
struct Desc: public DescBase
{
/// Initialize with default values
void init(Type typeIn)
{
this->type = typeIn;
this->size.init();
this->format = Format::Unknown;
this->arraySize = 0;
this->numMipLevels = 0;
this->sampleDesc.init();
this->bindFlags = 0;
this->cpuAccessFlags = 0;
}
/// Initialize different dimensions. For cubemap, use init2D
void init1D(Format formatIn, int widthIn, int numMipMapsIn = 0)
{
this->type = Type::Texture1D;
this->size.init(widthIn);
this->format = formatIn;
this->arraySize = 0;
this->numMipLevels = numMipMapsIn;
this->sampleDesc.init();
this->bindFlags = 0;
this->cpuAccessFlags = 0;
}
void init2D(Type typeIn, Format formatIn, int widthIn, int heightIn, int numMipMapsIn = 0)
{
assert(typeIn == Type::Texture2D || typeIn == Type::TextureCube);
this->type = typeIn;
this->size.init(widthIn, heightIn);
this->format = formatIn;
this->arraySize = 0;
this->numMipLevels = numMipMapsIn;
this->sampleDesc.init();
this->bindFlags = 0;
this->cpuAccessFlags = 0;
}
void init3D(Format formatIn, int widthIn, int heightIn, int depthIn, int numMipMapsIn = 0)
{
this->type = Type::Texture3D;
this->size.init(widthIn, heightIn, depthIn);
this->format = formatIn;
this->arraySize = 0;
this->numMipLevels = numMipMapsIn;
this->sampleDesc.init();
this->bindFlags = 0;
this->cpuAccessFlags = 0;
}
/// Given the type, calculates the number of mip maps. 0 on error
int calcNumMipLevels() const
{
const int maxDimensionSize = this->size.calcMaxDimension(type);
return (maxDimensionSize > 0) ? (_slang_gfx_log2Floor(maxDimensionSize) + 1) : 0;
}
/// Calculate the total number of sub resources. 0 on error.
int calcNumSubResources() const
{
const int numMipMaps =
(this->numMipLevels > 0) ? this->numMipLevels : calcNumMipLevels();
const int arrSize = (this->arraySize > 0) ? this->arraySize : 1;
switch (type)
{
case IResource::Type::Texture1D:
case IResource::Type::Texture2D:
{
return numMipMaps * arrSize;
}
case IResource::Type::Texture3D:
{
// can't have arrays of 3d textures
assert(this->arraySize <= 1);
return numMipMaps * this->size.depth;
}
case IResource::Type::TextureCube:
{
// There are 6 faces to a cubemap
return numMipMaps * arrSize * 6;
}
default:
return 0;
}
}
/// Calculate the effective array size - in essence the amount if mip map sets needed.
/// In practice takes into account if the arraySize is 0 (it's not an array, but it will still have at least one mip set)
/// and if the type is a cubemap (multiplies the amount of mip sets by 6)
int calcEffectiveArraySize() const
{
const int arrSize = (this->arraySize > 0) ? this->arraySize : 1;
switch (type)
{
case IResource::Type::Texture1D: // fallthru
case IResource::Type::Texture2D:
{
return arrSize;
}
case IResource::Type::TextureCube:
return arrSize * 6;
case IResource::Type::Texture3D:
return 1;
default:
return 0;
}
}
/// Use type to fix the size values (and array size).
/// For example a 1d texture, should have height and depth set to 1.
void fixSize()
{
switch (type)
{
case IResource::Type::Texture1D:
{
this->size.height = 1;
this->size.depth = 1;
break;
}
case IResource::Type::TextureCube:
case IResource::Type::Texture2D:
{
this->size.depth = 1;
break;
}
case IResource::Type::Texture3D:
{
// Can't have an array
this->arraySize = 0;
break;
}
default:
break;
}
}
/// Set up default parameters based on type and usage
void setDefaults(Usage initialUsage)
{
fixSize();
if (this->bindFlags == 0)
{
this->bindFlags = getDefaultBindFlagsFromUsage(initialUsage);
}
if (this->numMipLevels <= 0)
{
this->numMipLevels = calcNumMipLevels();
}
}
Size size;
int arraySize; ///< Array size
int numMipLevels; ///< Number of mip levels - if 0 will create all mip levels
Format format; ///< The resources format
SampleDesc sampleDesc; ///< How the resource is sampled
};
/// The ordering of the subResources is
/// forall (effectiveArraySize)
/// forall (mip levels)
/// forall (depth levels)
struct Data
{
ptrdiff_t* mipRowStrides; ///< The row stride for a mip map
int numMips; ///< The number of mip maps
const void*const* subResources; ///< Pointers to each full mip subResource
int numSubResources; ///< The total amount of subResources. Typically = numMips * depth * arraySize
};
virtual SLANG_NO_THROW Desc* SLANG_MCALL getDesc() = 0;
};
#define SLANG_UUID_ITextureResource \
{ \
0xcf88a31c, 0x6187, 0x46c5, { 0xa4, 0xb7, 0xeb, 0x58, 0xc7, 0x33, 0x40, 0x17 } \
}
// Needed for building on cygwin with gcc
#undef Always
#undef None
enum class ComparisonFunc : uint8_t
{
Never = 0,
Less = 0x01,
Equal = 0x02,
LessEqual = 0x03,
Greater = 0x04,
NotEqual = 0x05,
GreaterEqual = 0x06,
Always = 0x07,
};
enum class TextureFilteringMode
{
Point,
Linear,
};
enum class TextureAddressingMode
{
Wrap,
ClampToEdge,
ClampToBorder,
MirrorRepeat,
MirrorOnce,
};
enum class TextureReductionOp
{
Average,
Comparison,
Minimum,
Maximum,
};
class ISamplerState : public ISlangUnknown
{
public:
struct Desc
{
TextureFilteringMode minFilter = TextureFilteringMode::Linear;
TextureFilteringMode magFilter = TextureFilteringMode::Linear;
TextureFilteringMode mipFilter = TextureFilteringMode::Linear;
TextureReductionOp reductionOp = TextureReductionOp::Average;
TextureAddressingMode addressU = TextureAddressingMode::Wrap;
TextureAddressingMode addressV = TextureAddressingMode::Wrap;
TextureAddressingMode addressW = TextureAddressingMode::Wrap;
float mipLODBias = 0.0f;
uint32_t maxAnisotropy = 1;
ComparisonFunc comparisonFunc = ComparisonFunc::Never;
float borderColor[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
float minLOD = -FLT_MAX;
float maxLOD = FLT_MAX;
};
};
#define SLANG_UUID_ISamplerState \
{ \
0x8b8055df, 0x9377, 0x401d, { 0x91, 0xff, 0x3f, 0xa3, 0xbf, 0x66, 0x64, 0xf4 } \
}
enum class DescriptorSlotType
{
Unknown,
Sampler,
CombinedImageSampler,
SampledImage,
StorageImage,
UniformTexelBuffer,
StorageTexelBuffer,
UniformBuffer,
ReadOnlyStorageBuffer,
StorageBuffer,
DynamicUniformBuffer,
DynamicStorageBuffer,
InputAttachment,
RootConstant,
InlineUniformBlock,
RayTracingAccelerationStructure,
};
class IDescriptorSetLayout : public ISlangUnknown
{
public:
struct SlotRangeDesc
{
DescriptorSlotType type = DescriptorSlotType::Unknown;
UInt count = 1;
/// The underlying API-specific binding/register to use for this slot range.
///
/// A value of `-1` indicates that the implementation should
/// automatically compute the binding/register to use
/// based on the preceeding slot range(s).
///
/// Some implementations do not have a concept of bindings/regsiters
/// for slot ranges, and will ignore this field.
///
Int binding = -1;
SlotRangeDesc()
{}
SlotRangeDesc(
DescriptorSlotType type,
UInt count = 1)
: type(type)
, count(count)
{}
};
struct Desc
{
UInt slotRangeCount = 0;
SlotRangeDesc const* slotRanges = nullptr;
};
};
#define SLANG_UUID_IDescriptorSetLayout \
{ \
0x9fe39a2f, 0xdf8b, 0x4690, { 0x90, 0x6a, 0x10, 0x1e, 0xed, 0xf9, 0xbe, 0xc0 } \
}
class IPipelineLayout : public ISlangUnknown
{
public:
struct DescriptorSetDesc
{
IDescriptorSetLayout* layout = nullptr;
/// The underlying API-specific space/set number to use for this set.
///
/// A value of `-1` indicates that the implementation should
/// automatically compute the space/set to use basd on
/// the preceeding set(s)
///
/// Some implementations do not have a concept of space/set numbers
/// for descriptor sets, and will ignore this field.
///
Int space = -1;
DescriptorSetDesc()
{}
DescriptorSetDesc(
IDescriptorSetLayout* layout)
: layout(layout)
{}
};
struct Desc
{
UInt renderTargetCount = 0;
UInt descriptorSetCount = 0;
DescriptorSetDesc const* descriptorSets = nullptr;
};
};
#define SLANG_UUID_IPipelineLayout \
{ \
0x9d644a9a, 0x3e6f, 0x4350, { 0xa3, 0x5a, 0xe8, 0xe3, 0xbc, 0xef, 0xb9, 0xcf } \
}
class IResourceView : public ISlangUnknown
{
public:
enum class Type
{
Unknown,
RenderTarget,
DepthStencil,
ShaderResource,
UnorderedAccess,
};
struct Desc
{
Type type;
Format format;
};
};
#define SLANG_UUID_IResourceView \
{ \
0x7b6c4926, 0x884, 0x408c, { 0xad, 0x8a, 0x50, 0x3a, 0x8e, 0x23, 0x98, 0xa4 } \
}
class IDescriptorSet : public ISlangUnknown
{
public:
virtual SLANG_NO_THROW void SLANG_MCALL setConstantBuffer(UInt range, UInt index, IBufferResource* buffer) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL
setResource(UInt range, UInt index, IResourceView* view) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL
setSampler(UInt range, UInt index, ISamplerState* sampler) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL setCombinedTextureSampler(
UInt range,
UInt index,
IResourceView* textureView,
ISamplerState* sampler) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL
setRootConstants(
UInt range,
UInt offset,
UInt size,
void const* data) = 0;
};
#define SLANG_UUID_IDescriptorSet \
{ \
0x29a881ea, 0xd7, 0x41d4, { 0xa3, 0x2d, 0x6c, 0x78, 0x4b, 0x79, 0xda, 0x2e } \
}
struct ShaderOffset
{
SlangInt uniformOffset = 0;
SlangInt bindingRangeIndex = 0;
SlangInt bindingArrayIndex = 0;
};
class IShaderObjectLayout : public ISlangUnknown
{};
#define SLANG_UUID_IShaderObjectLayout \
{ \
0x27f3f67e, 0xa49d, 0x4aae, { 0xa6, 0xd, 0xfa, 0xc2, 0x6b, 0x1c, 0x10, 0x7c } \
}
class IShaderObject : public ISlangUnknown
{
public:
SLANG_NO_THROW ComPtr<IShaderObject> SLANG_MCALL getObject(ShaderOffset const& offset)
{
ComPtr<IShaderObject> object = nullptr;
SLANG_RETURN_NULL_ON_FAIL(getObject(offset, object.writeRef()));
return object;
}
virtual SLANG_NO_THROW slang::TypeLayoutReflection* SLANG_MCALL getElementTypeLayout() = 0;
virtual SLANG_NO_THROW UInt SLANG_MCALL getEntryPointCount() = 0;
ComPtr<IShaderObject> getEntryPoint(UInt index)
{
ComPtr<IShaderObject> entryPoint = nullptr;
SLANG_RETURN_NULL_ON_FAIL(getEntryPoint(index, entryPoint.writeRef()));
return entryPoint;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
getEntryPoint(UInt index, IShaderObject** entryPoint) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL
setData(ShaderOffset const& offset, void const* data, size_t size) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL
getObject(ShaderOffset const& offset, IShaderObject** object) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL
setObject(ShaderOffset const& offset, IShaderObject* object) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL
setResource(ShaderOffset const& offset, IResourceView* resourceView) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL
setSampler(ShaderOffset const& offset, ISamplerState* sampler) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL setCombinedTextureSampler(
ShaderOffset const& offset, IResourceView* textureView, ISamplerState* sampler) = 0;
};
#define SLANG_UUID_IShaderObject \
{ \
0xc1fa997e, 0x5ca2, 0x45ae, { 0x9b, 0xcb, 0xc4, 0x35, 0x9e, 0x85, 0x5, 0x85 } \
}
enum class StencilOp : uint8_t
{
Keep,
Zero,
Replace,
IncrementSaturate,
DecrementSaturate,
Invert,
IncrementWrap,
DecrementWrap,
};
enum class FillMode : uint8_t
{
Solid,
Wireframe,
};
enum class CullMode : uint8_t
{
None,
Front,
Back,
};
enum class FrontFaceMode : uint8_t
{
CounterClockwise,
Clockwise,
};
struct DepthStencilOpDesc
{
StencilOp stencilFailOp = StencilOp::Keep;
StencilOp stencilDepthFailOp = StencilOp::Keep;
StencilOp stencilPassOp = StencilOp::Keep;
ComparisonFunc stencilFunc = ComparisonFunc::Always;
};
struct DepthStencilDesc
{
bool depthTestEnable = true;
bool depthWriteEnable = true;
ComparisonFunc depthFunc = ComparisonFunc::Less;
bool stencilEnable = false;
uint32_t stencilReadMask = 0xFFFFFFFF;
uint32_t stencilWriteMask = 0xFFFFFFFF;
DepthStencilOpDesc frontFace;
DepthStencilOpDesc backFace;
uint32_t stencilRef = 0;
};
struct RasterizerDesc
{
FillMode fillMode = FillMode::Solid;
CullMode cullMode = CullMode::Back;
FrontFaceMode frontFace = FrontFaceMode::CounterClockwise;
int32_t depthBias = 0;
float depthBiasClamp = 0.0f;
float slopeScaledDepthBias = 0.0f;
bool depthClipEnable = true;
bool scissorEnable = false;
bool multisampleEnable = false;
bool antialiasedLineEnable = false;
};
enum class LogicOp
{
NoOp,
};
enum class BlendOp
{
Add,
Subtract,
ReverseSubtract,
Min,
Max,
};
enum class BlendFactor
{
Zero,
One,
SrcColor,
InvSrcColor,
SrcAlpha,
InvSrcAlpha,
DestAlpha,
InvDestAlpha,
DestColor,
InvDestColor,
SrcAlphaSaturate,
BlendColor,
InvBlendColor,
SecondarySrcColor,
InvSecondarySrcColor,
SecondarySrcAlpha,
InvSecondarySrcAlpha,
};
namespace RenderTargetWriteMask
{
typedef uint8_t Type;
enum
{
EnableNone = 0,
EnableRed = 0x01,
EnableGreen = 0x02,
EnableBlue = 0x04,
EnableAlpha = 0x08,
EnableAll = 0x0F,
};
};
typedef RenderTargetWriteMask::Type RenderTargetWriteMaskT;
struct AspectBlendDesc
{
BlendFactor srcFactor = BlendFactor::One;
BlendFactor dstFactor = BlendFactor::Zero;
BlendOp op = BlendOp::Add;
};
struct TargetBlendDesc
{
AspectBlendDesc color;
AspectBlendDesc alpha;
LogicOp logicOp = LogicOp::NoOp;
RenderTargetWriteMaskT writeMask = RenderTargetWriteMask::EnableAll;
};
struct BlendDesc
{
TargetBlendDesc const* targets = nullptr;
UInt targetCount = 0;
bool alphaToCoverateEnable = false;
};
struct GraphicsPipelineStateDesc
{
IShaderProgram* program;
// If `pipelineLayout` is null, then layout information will be extracted
// from `program`, which must have been created with Slang reflection info.
IPipelineLayout* pipelineLayout = nullptr;
IInputLayout* inputLayout;
UInt framebufferWidth;
UInt framebufferHeight;
UInt renderTargetCount = 0; // Only used if `pipelineLayout` is non-null
DepthStencilDesc depthStencil;
RasterizerDesc rasterizer;
BlendDesc blend;
};
struct ComputePipelineStateDesc
{
IShaderProgram* program;
// If `pipelineLayout` is null, then layout information will be extracted
// from `program`, which must have been created with Slang reflection info.
IPipelineLayout* pipelineLayout = nullptr;
};
class IPipelineState : public ISlangUnknown
{
};
#define SLANG_UUID_IPipelineState \
{ \
0xca7e57d, 0x8a90, 0x44f3, { 0xbd, 0xb1, 0xfe, 0x9b, 0x35, 0x3f, 0x5a, 0x72 } \
}
struct ScissorRect
{
Int minX;
Int minY;
Int maxX;
Int maxY;
};
struct Viewport
{
float originX = 0.0f;
float originY = 0.0f;
float extentX = 0.0f;
float extentY = 0.0f;
float minZ = 0.0f;
float maxZ = 1.0f;
};
class IRenderer: public ISlangUnknown
{
public:
struct SlangDesc
{
slang::IGlobalSession* slangGlobalSession = nullptr; // (optional) A slang global session object. If null will create automatically.
SlangMatrixLayoutMode defaultMatrixLayoutMode = SLANG_MATRIX_LAYOUT_ROW_MAJOR;
char const* const* searchPaths = nullptr;
SlangInt searchPathCount = 0;
slang::PreprocessorMacroDesc const* preprocessorMacros = nullptr;
SlangInt preprocessorMacroCount = 0;
const char* targetProfile = nullptr; // (optional) Target shader profile. If null this will be set to platform dependent default.
SlangFloatingPointMode floatingPointMode = SLANG_FLOATING_POINT_MODE_DEFAULT;
SlangOptimizationLevel optimizationLevel = SLANG_OPTIMIZATION_LEVEL_DEFAULT;
};
struct Desc
{
RendererType rendererType; // The underlying API/Platform of the renderer.
int width = 0; // Width in pixels
int height = 0; // height in pixels
const char* adapter = nullptr; // Name to identify the adapter to use
int requiredFeatureCount = 0; // Number of required features.
const char** requiredFeatures = nullptr; // Array of required feature names, whose size is `requiredFeatureCount`.
int nvapiExtnSlot = -1; // The slot (typically UAV) used to identify NVAPI intrinsics. If >=0 NVAPI is required.
ISlangFileSystem* shaderCacheFileSystem = nullptr; // The file system for loading cached shader kernels.
SlangDesc slang = {}; // Configurations for Slang.
};
virtual SLANG_NO_THROW bool SLANG_MCALL hasFeature(const char* feature) = 0;
/// Returns a list of features supported by the renderer.
virtual SLANG_NO_THROW Result SLANG_MCALL getFeatures(const char** outFeatures, UInt bufferSize, UInt* outFeatureCount) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL getSlangSession(slang::ISession** outSlangSession) = 0;
inline ComPtr<slang::ISession> getSlangSession()
{
ComPtr<slang::ISession> result;
getSlangSession(result.writeRef());
return result;
}
virtual SLANG_NO_THROW void SLANG_MCALL setClearColor(const float color[4]) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL clearFrame() = 0;
virtual SLANG_NO_THROW void SLANG_MCALL presentFrame() = 0;
virtual SLANG_NO_THROW ITextureResource::Desc SLANG_MCALL getSwapChainTextureDesc() = 0;
/// Create a texture resource. initData holds the initialize data to set the contents of the texture when constructed.
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureResource(
IResource::Usage initialUsage,
const ITextureResource::Desc& desc,
const ITextureResource::Data* initData,
ITextureResource** outResource) = 0;
/// Create a texture resource. initData holds the initialize data to set the contents of the texture when constructed.
inline SLANG_NO_THROW ComPtr<ITextureResource> createTextureResource(
IResource::Usage initialUsage,
const ITextureResource::Desc& desc,
const ITextureResource::Data* initData = nullptr)
{
ComPtr<ITextureResource> resource;
SLANG_RETURN_NULL_ON_FAIL(createTextureResource(initialUsage, desc, initData, resource.writeRef()));
return resource;
}
/// Create a buffer resource
virtual SLANG_NO_THROW Result SLANG_MCALL createBufferResource(
IResource::Usage initialUsage,
const IBufferResource::Desc& desc,
const void* initData,
IBufferResource** outResource) = 0;
inline SLANG_NO_THROW ComPtr<IBufferResource> createBufferResource(
IResource::Usage initialUsage,
const IBufferResource::Desc& desc,
const void* initData = nullptr)
{
ComPtr<IBufferResource> resource;
SLANG_RETURN_NULL_ON_FAIL(createBufferResource(initialUsage, desc, initData, resource.writeRef()));
return resource;
}
virtual SLANG_NO_THROW Result SLANG_MCALL
createSamplerState(ISamplerState::Desc const& desc, ISamplerState** outSampler) = 0;
inline ComPtr<ISamplerState> createSamplerState(ISamplerState::Desc const& desc)
{
ComPtr<ISamplerState> sampler;
SLANG_RETURN_NULL_ON_FAIL(createSamplerState(desc, sampler.writeRef()));
return sampler;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createTextureView(
ITextureResource* texture, IResourceView::Desc const& desc, IResourceView** outView) = 0;
inline ComPtr<IResourceView> createTextureView(ITextureResource* texture, IResourceView::Desc const& desc)
{
ComPtr<IResourceView> view;
SLANG_RETURN_NULL_ON_FAIL(createTextureView(texture, desc, view.writeRef()));
return view;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createBufferView(
IBufferResource* buffer, IResourceView::Desc const& desc, IResourceView** outView) = 0;
inline ComPtr<IResourceView> createBufferView(IBufferResource* buffer, IResourceView::Desc const& desc)
{
ComPtr<IResourceView> view;
SLANG_RETURN_NULL_ON_FAIL(createBufferView(buffer, desc, view.writeRef()));
return view;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createInputLayout(
const InputElementDesc* inputElements, UInt inputElementCount, IInputLayout** outLayout) = 0;
inline ComPtr<IInputLayout> createInputLayout(const InputElementDesc* inputElements, UInt inputElementCount)
{
ComPtr<IInputLayout> layout;
SLANG_RETURN_NULL_ON_FAIL(createInputLayout(inputElements, inputElementCount, layout.writeRef()));
return layout;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createDescriptorSetLayout(
const IDescriptorSetLayout::Desc& desc, IDescriptorSetLayout** outLayout) = 0;
inline ComPtr<IDescriptorSetLayout> createDescriptorSetLayout(const IDescriptorSetLayout::Desc& desc)
{
ComPtr<IDescriptorSetLayout> layout;
SLANG_RETURN_NULL_ON_FAIL(createDescriptorSetLayout(desc, layout.writeRef()));
return layout;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createShaderObjectLayout(
slang::TypeLayoutReflection* typeLayout, IShaderObjectLayout** outLayout) = 0;
inline ComPtr<IShaderObjectLayout> createShaderObjectLayout(slang::TypeLayoutReflection* typeLayout)
{
ComPtr<IShaderObjectLayout> layout;
SLANG_RETURN_NULL_ON_FAIL(createShaderObjectLayout(typeLayout, layout.writeRef()));
return layout;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createShaderObject(IShaderObjectLayout* layout, IShaderObject** outObject) = 0;
inline ComPtr<IShaderObject> createShaderObject(IShaderObjectLayout* layout)
{
ComPtr<IShaderObject> object;
SLANG_RETURN_NULL_ON_FAIL(createShaderObject(layout, object.writeRef()));
return object;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createRootShaderObject(IShaderProgram* program, IShaderObject** outObject) = 0;
inline ComPtr<IShaderObject> createRootShaderObject(IShaderProgram* program)
{
ComPtr<IShaderObject> object;
SLANG_RETURN_NULL_ON_FAIL(createRootShaderObject(program, object.writeRef()));
return object;
}
virtual SLANG_NO_THROW Result SLANG_MCALL bindRootShaderObject(PipelineType pipelineType, IShaderObject* object) = 0;
virtual SLANG_NO_THROW Result SLANG_MCALL createPipelineLayout(const IPipelineLayout::Desc& desc, IPipelineLayout** outLayout) = 0;
inline ComPtr<IPipelineLayout> createPipelineLayout(const IPipelineLayout::Desc& desc)
{
ComPtr<IPipelineLayout> layout;
SLANG_RETURN_NULL_ON_FAIL(createPipelineLayout(desc, layout.writeRef()));
return layout;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createDescriptorSet(IDescriptorSetLayout* layout, IDescriptorSet** outDescriptorSet) = 0;
inline ComPtr<IDescriptorSet> createDescriptorSet(IDescriptorSetLayout* layout)
{
ComPtr<IDescriptorSet> descriptorSet;
SLANG_RETURN_NULL_ON_FAIL(createDescriptorSet(layout, descriptorSet.writeRef()));
return descriptorSet;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createProgram(const IShaderProgram::Desc& desc, IShaderProgram** outProgram) = 0;
inline ComPtr<IShaderProgram> createProgram(const IShaderProgram::Desc& desc)
{
ComPtr<IShaderProgram> program;
SLANG_RETURN_NULL_ON_FAIL(createProgram(desc, program.writeRef()));
return program;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createGraphicsPipelineState(
const GraphicsPipelineStateDesc& desc,
IPipelineState** outState) = 0;
inline ComPtr<IPipelineState> createGraphicsPipelineState(
const GraphicsPipelineStateDesc& desc)
{
ComPtr<IPipelineState> state;
SLANG_RETURN_NULL_ON_FAIL(createGraphicsPipelineState(desc, state.writeRef()));
return state;
}
virtual SLANG_NO_THROW Result SLANG_MCALL createComputePipelineState(
const ComputePipelineStateDesc& desc,
IPipelineState** outState) = 0;
inline ComPtr<IPipelineState> createComputePipelineState(
const ComputePipelineStateDesc& desc)
{
ComPtr<IPipelineState> state;
SLANG_RETURN_NULL_ON_FAIL(createComputePipelineState(desc, state.writeRef()));
return state;
}
/// Captures the back buffer and stores the result in surfaceOut. If the surface contains data - it will either be overwritten (if same size and format), or freed and a re-allocated.
virtual SLANG_NO_THROW SlangResult SLANG_MCALL captureScreenSurface(void* buffer, size_t *inOutBufferSize, size_t* outRowPitch, size_t* outPixelSize) = 0;
virtual SLANG_NO_THROW void* SLANG_MCALL map(IBufferResource* buffer, MapFlavor flavor) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL unmap(IBufferResource* buffer) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL setPrimitiveTopology(PrimitiveTopology topology) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL setDescriptorSet(
PipelineType pipelineType,
IPipelineLayout* layout,
UInt index,
IDescriptorSet* descriptorSet) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL setVertexBuffers(
UInt startSlot,
UInt slotCount,
IBufferResource* const* buffers,
const UInt* strides,
const UInt* offsets) = 0;
inline void setVertexBuffer(UInt slot, IBufferResource* buffer, UInt stride, UInt offset = 0);
virtual SLANG_NO_THROW void SLANG_MCALL
setIndexBuffer(IBufferResource* buffer, Format indexFormat, UInt offset = 0) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL setDepthStencilTarget(IResourceView* depthStencilView) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL setViewports(UInt count, Viewport const* viewports) = 0;
inline void setViewport(Viewport const& viewport)
{
setViewports(1, &viewport);
}
virtual SLANG_NO_THROW void SLANG_MCALL setScissorRects(UInt count, ScissorRect const* rects) = 0;
inline void setScissorRect(ScissorRect const& rect)
{
setScissorRects(1, &rect);
}
virtual SLANG_NO_THROW void SLANG_MCALL setPipelineState(IPipelineState* state) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL draw(UInt vertexCount, UInt startVertex = 0) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL drawIndexed(UInt indexCount, UInt startIndex = 0, UInt baseVertex = 0) = 0;
virtual SLANG_NO_THROW void SLANG_MCALL dispatchCompute(int x, int y, int z) = 0;
/// Commit any buffered state changes or draw calls.
/// presentFrame will commitAll implicitly before doing a present
virtual SLANG_NO_THROW void SLANG_MCALL submitGpuWork() = 0;
/// Blocks until Gpu work is complete
virtual SLANG_NO_THROW void SLANG_MCALL waitForGpu() = 0;
/// Get the type of this renderer
virtual SLANG_NO_THROW RendererType SLANG_MCALL getRendererType() const = 0;
};
#define SLANG_UUID_IRenderer \
{ \
0x715bdf26, 0x5135, 0x11eb, { 0xAE, 0x93, 0x02, 0x42, 0xAC, 0x13, 0x00, 0x02 } \
}
// ----------------------------------------------------------------------------------------
inline void IRenderer::setVertexBuffer(UInt slot, IBufferResource* buffer, UInt stride, UInt offset)
{
setVertexBuffers(slot, 1, &buffer, &stride, &offset);
}
// Global public functions
extern "C"
{
/// Gets the size in bytes of a Format type. Returns 0 if a size is not defined/invalid
SLANG_GFX_API size_t SLANG_MCALL gfxGetFormatSize(Format format);
/// Gets the binding style from the type
SLANG_GFX_API BindingStyle SLANG_MCALL gfxGetBindingStyle(RendererType type);
/// Given a renderer type, gets a projection style
SLANG_GFX_API ProjectionStyle SLANG_MCALL gfxGetProjectionStyle(RendererType type);
/// Given the projection style returns an 'identity' matrix, which ensures x,y mapping to pixels
/// is the same on all targets
SLANG_GFX_API void SLANG_MCALL
gfxGetIdentityProjection(ProjectionStyle style, float projMatrix[16]);
/// Get the name of the renderer
SLANG_GFX_API const char* SLANG_MCALL gfxGetRendererName(RendererType type);
/// Given a type returns a function that can construct it, or nullptr if there isn't one
SLANG_GFX_API SlangResult SLANG_MCALL gfxCreateRenderer(const IRenderer::Desc* desc, void* windowHandle, IRenderer** outRenderer);
}
}// renderer_test
<file_sep>/tools/gfx/render.cpp
// render.cpp
#include "renderer-shared.h"
#include "../../source/core/slang-math.h"
#include "d3d11/render-d3d11.h"
#include "d3d12/render-d3d12.h"
#include "open-gl/render-gl.h"
#include "vulkan/render-vk.h"
#include "cuda/render-cuda.h"
#include <cstring>
namespace gfx {
using namespace Slang;
static const IResource::DescBase s_emptyDescBase = {};
/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Global Renderer Functions !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
static const uint8_t s_formatSize[] = {
0, // Unknown,
uint8_t(sizeof(float) * 4), // RGBA_Float32,
uint8_t(sizeof(float) * 3), // RGB_Float32,
uint8_t(sizeof(float) * 2), // RG_Float32,
uint8_t(sizeof(float) * 1), // R_Float32,
uint8_t(sizeof(uint32_t)), // RGBA_Unorm_UInt8,
uint8_t(sizeof(uint16_t)), // R_UInt16,
uint8_t(sizeof(uint32_t)), // R_UInt32,
uint8_t(sizeof(float)), // D_Float32,
uint8_t(sizeof(uint32_t)), // D_Unorm24_S8,
};
static const BindingStyle s_rendererTypeToBindingStyle[] = {
BindingStyle::Unknown, // Unknown,
BindingStyle::DirectX, // DirectX11,
BindingStyle::DirectX, // DirectX12,
BindingStyle::OpenGl, // OpenGl,
BindingStyle::Vulkan, // Vulkan
BindingStyle::CPU, // CPU
BindingStyle::CUDA, // CUDA
};
static void _compileTimeAsserts()
{
SLANG_COMPILE_TIME_ASSERT(SLANG_COUNT_OF(s_formatSize) == int(Format::CountOf));
SLANG_COMPILE_TIME_ASSERT(
SLANG_COUNT_OF(s_rendererTypeToBindingStyle) == int(RendererType::CountOf));
}
extern "C"
{
size_t SLANG_MCALL gfxGetFormatSize(Format format)
{
return s_formatSize[int(format)];
}
BindingStyle SLANG_MCALL gfxGetBindingStyle(RendererType type)
{
return s_rendererTypeToBindingStyle[int(type)];
}
const char* SLANG_MCALL gfxGetRendererName(RendererType type)
{
switch (type)
{
case RendererType::DirectX11:
return "DirectX11";
case RendererType::DirectX12:
return "DirectX12";
case RendererType::OpenGl:
return "OpenGL";
case RendererType::Vulkan:
return "Vulkan";
case RendererType::Unknown:
return "Unknown";
case RendererType::CPU:
return "CPU";
case RendererType::CUDA:
return "CUDA";
default:
return "?!?";
}
}
SLANG_GFX_API SlangResult SLANG_MCALL gfxCreateRenderer(const IRenderer::Desc* desc, void* windowHandle, IRenderer** outRenderer)
{
switch (desc->rendererType)
{
#if SLANG_WINDOWS_FAMILY
case RendererType::DirectX11:
{
return createD3D11Renderer(desc, windowHandle, outRenderer);
}
case RendererType::DirectX12:
{
return createD3D12Renderer(desc, windowHandle, outRenderer);
}
case RendererType::OpenGl:
{
return createGLRenderer(desc, windowHandle, outRenderer);
}
case RendererType::Vulkan:
{
return createVKRenderer(desc, windowHandle, outRenderer);
}
case RendererType::CUDA:
{
return createCUDARenderer(desc, windowHandle, outRenderer);
}
#endif
default:
return SLANG_FAIL;
}
}
ProjectionStyle SLANG_MCALL gfxGetProjectionStyle(RendererType type)
{
switch (type)
{
case RendererType::DirectX11:
case RendererType::DirectX12:
{
return ProjectionStyle::DirectX;
}
case RendererType::OpenGl:
return ProjectionStyle::OpenGl;
case RendererType::Vulkan:
return ProjectionStyle::Vulkan;
case RendererType::Unknown:
return ProjectionStyle::Unknown;
default:
{
assert(!"Unhandled type");
return ProjectionStyle::Unknown;
}
}
}
void SLANG_MCALL gfxGetIdentityProjection(ProjectionStyle style, float projMatrix[16])
{
switch (style)
{
case ProjectionStyle::DirectX:
case ProjectionStyle::OpenGl:
{
static const float kIdentity[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(projMatrix, kIdentity, sizeof(kIdentity));
break;
}
case ProjectionStyle::Vulkan:
{
static const float kIdentity[] = {1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
::memcpy(projMatrix, kIdentity, sizeof(kIdentity));
break;
}
default:
{
assert(!"Not handled");
}
}
}
}
} // renderer_test
<file_sep>/tools/gfx/vulkan/render-vk.h
// render-vk.h
#pragma once
#include <cstdint>
#include "../renderer-shared.h"
namespace gfx {
SlangResult SLANG_MCALL createVKRenderer(const IRenderer::Desc* desc, void* windowHandle, IRenderer** outRenderer);
} // gfx
<file_sep>/tools/gfx/d3d12/render-d3d12.h
// render-d3d12.h
#pragma once
#include "../renderer-shared.h"
namespace gfx
{
SlangResult SLANG_MCALL createD3D12Renderer(const IRenderer::Desc* desc, void* windowHandle, IRenderer** outRenderer);
} // gfx
<file_sep>/tools/graphics-app-framework/gui.h
// gui.h
#pragma once
#include "tools/gfx/render.h"
#include "vector-math.h"
#include "window.h"
#include "slang-com-ptr.h"
#include "external/imgui/imgui.h"
#include "source/core/slang-basic.h"
namespace gfx {
struct GUI : Slang::RefObject
{
GUI(Window* window, IRenderer* renderer);
~GUI();
void beginFrame();
void endFrame();
private:
Slang::ComPtr<IRenderer> renderer;
Slang::ComPtr<IPipelineState> pipelineState;
Slang::ComPtr<IDescriptorSetLayout> descriptorSetLayout;
Slang::ComPtr<IPipelineLayout> pipelineLayout;
Slang::ComPtr<ISamplerState> samplerState;
};
} // gfx
<file_sep>/tools/gfx/renderer-shared.cpp
#include "renderer-shared.h"
#include "render-graphics-common.h"
#include "core/slang-io.h"
#include "core/slang-token-reader.h"
using namespace Slang;
namespace gfx
{
const Slang::Guid GfxGUID::IID_ISlangUnknown = SLANG_UUID_ISlangUnknown;
const Slang::Guid GfxGUID::IID_IDescriptorSetLayout = SLANG_UUID_IDescriptorSetLayout;
const Slang::Guid GfxGUID::IID_IDescriptorSet = SLANG_UUID_IDescriptorSet;
const Slang::Guid GfxGUID::IID_IShaderProgram = SLANG_UUID_IShaderProgram;
const Slang::Guid GfxGUID::IID_IPipelineLayout = SLANG_UUID_IPipelineLayout;
const Slang::Guid GfxGUID::IID_IInputLayout = SLANG_UUID_IInputLayout;
const Slang::Guid GfxGUID::IID_IPipelineState = SLANG_UUID_IPipelineState;
const Slang::Guid GfxGUID::IID_IResourceView = SLANG_UUID_IResourceView;
const Slang::Guid GfxGUID::IID_ISamplerState = SLANG_UUID_ISamplerState;
const Slang::Guid GfxGUID::IID_IResource = SLANG_UUID_IResource;
const Slang::Guid GfxGUID::IID_IBufferResource = SLANG_UUID_IBufferResource;
const Slang::Guid GfxGUID::IID_ITextureResource = SLANG_UUID_ITextureResource;
const Slang::Guid GfxGUID::IID_IRenderer = SLANG_UUID_IRenderer;
const Slang::Guid GfxGUID::IID_IShaderObjectLayout = SLANG_UUID_IShaderObjectLayout;
const Slang::Guid GfxGUID::IID_IShaderObject = SLANG_UUID_IShaderObject;
gfx::StageType translateStage(SlangStage slangStage)
{
switch (slangStage)
{
default:
SLANG_ASSERT(!"unhandled case");
return gfx::StageType::Unknown;
#define CASE(FROM, TO) \
case SLANG_STAGE_##FROM: \
return gfx::StageType::TO
CASE(VERTEX, Vertex);
CASE(HULL, Hull);
CASE(DOMAIN, Domain);
CASE(GEOMETRY, Geometry);
CASE(FRAGMENT, Fragment);
CASE(COMPUTE, Compute);
CASE(RAY_GENERATION, RayGeneration);
CASE(INTERSECTION, Intersection);
CASE(ANY_HIT, AnyHit);
CASE(CLOSEST_HIT, ClosestHit);
CASE(MISS, Miss);
CASE(CALLABLE, Callable);
#undef CASE
}
}
IResource* BufferResource::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResource ||
guid == GfxGUID::IID_IBufferResource)
return static_cast<IBufferResource*>(this);
return nullptr;
}
SLANG_NO_THROW IResource::Type SLANG_MCALL BufferResource::getType() { return m_type; }
SLANG_NO_THROW IBufferResource::Desc* SLANG_MCALL BufferResource::getDesc() { return &m_desc; }
IResource* TextureResource::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResource ||
guid == GfxGUID::IID_ITextureResource)
return static_cast<ITextureResource*>(this);
return nullptr;
}
SLANG_NO_THROW IResource::Type SLANG_MCALL TextureResource::getType() { return m_type; }
SLANG_NO_THROW ITextureResource::Desc* SLANG_MCALL TextureResource::getDesc() { return &m_desc; }
gfx::StageType mapStage(SlangStage stage)
{
switch( stage )
{
default:
return gfx::StageType::Unknown;
case SLANG_STAGE_AMPLIFICATION: return gfx::StageType::Amplification;
case SLANG_STAGE_ANY_HIT: return gfx::StageType::AnyHit;
case SLANG_STAGE_CALLABLE: return gfx::StageType::Callable;
case SLANG_STAGE_CLOSEST_HIT: return gfx::StageType::ClosestHit;
case SLANG_STAGE_COMPUTE: return gfx::StageType::Compute;
case SLANG_STAGE_DOMAIN: return gfx::StageType::Domain;
case SLANG_STAGE_FRAGMENT: return gfx::StageType::Fragment;
case SLANG_STAGE_GEOMETRY: return gfx::StageType::Geometry;
case SLANG_STAGE_HULL: return gfx::StageType::Hull;
case SLANG_STAGE_INTERSECTION: return gfx::StageType::Intersection;
case SLANG_STAGE_MESH: return gfx::StageType::Mesh;
case SLANG_STAGE_MISS: return gfx::StageType::Miss;
case SLANG_STAGE_RAY_GENERATION: return gfx::StageType::RayGeneration;
case SLANG_STAGE_VERTEX: return gfx::StageType::Vertex;
}
}
Result createProgramFromSlang(IRenderer* renderer, IShaderProgram::Desc const& originalDesc, IShaderProgram** outProgram)
{
SlangInt targetIndex = 0;
auto slangProgram = originalDesc.slangProgram;
auto programLayout = slangProgram->getLayout(targetIndex);
if(!programLayout)
return SLANG_FAIL;
Int entryPointCount = (Int) programLayout->getEntryPointCount();
if(entryPointCount == 0)
return SLANG_FAIL;
List<IShaderProgram::KernelDesc> kernelDescs;
List<ComPtr<slang::IBlob>> kernelBlobs;
for( Int i = 0; i < entryPointCount; ++i )
{
ComPtr<slang::IBlob> entryPointCodeBlob;
SLANG_RETURN_ON_FAIL(slangProgram->getEntryPointCode(i, targetIndex, entryPointCodeBlob.writeRef()));
auto entryPointLayout = programLayout->getEntryPointByIndex(i);
kernelBlobs.add(entryPointCodeBlob);
IShaderProgram::KernelDesc kernelDesc;
kernelDesc.codeBegin = entryPointCodeBlob->getBufferPointer();
kernelDesc.codeEnd = (const char*) kernelDesc.codeBegin + entryPointCodeBlob->getBufferSize();
kernelDesc.entryPointName = entryPointLayout->getName();
kernelDesc.stage = mapStage(entryPointLayout->getStage());
kernelDescs.add(kernelDesc);
}
SLANG_ASSERT(kernelDescs.getCount() == entryPointCount);
IShaderProgram::Desc programDesc;
programDesc.pipelineType = originalDesc.pipelineType;
programDesc.slangProgram = slangProgram;
programDesc.kernelCount = kernelDescs.getCount();
programDesc.kernels = kernelDescs.getBuffer();
return renderer->createProgram(programDesc, outProgram);
}
IShaderObject* gfx::ShaderObjectBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IShaderObject)
return static_cast<IShaderObject*>(this);
return nullptr;
}
IShaderProgram* gfx::ShaderProgramBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IShaderProgram)
return static_cast<IShaderProgram*>(this);
return nullptr;
}
IPipelineState* gfx::PipelineStateBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IPipelineState)
return static_cast<IPipelineState*>(this);
return nullptr;
}
void PipelineStateBase::initializeBase(const PipelineStateDesc& inDesc)
{
desc = inDesc;
auto program = desc.getProgram();
isSpecializable = (program->slangProgram && program->slangProgram->getSpecializationParamCount() != 0);
}
IRenderer* gfx::RendererBase::getInterface(const Guid& guid)
{
return (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IRenderer)
? static_cast<IRenderer*>(this)
: nullptr;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::initialize(const Desc& desc, void* inWindowHandle)
{
SLANG_UNUSED(inWindowHandle);
shaderCache.init(desc.shaderCacheFileSystem);
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::getFeatures(
const char** outFeatures, UInt bufferSize, UInt* outFeatureCount)
{
if (bufferSize >= (UInt)m_features.getCount())
{
for (Index i = 0; i < m_features.getCount(); i++)
{
outFeatures[i] = m_features[i].getUnownedSlice().begin();
}
}
if (outFeatureCount)
*outFeatureCount = (UInt)m_features.getCount();
return SLANG_OK;
}
SLANG_NO_THROW bool SLANG_MCALL RendererBase::hasFeature(const char* featureName)
{
return m_features.findFirstIndex([&](Slang::String x) { return x == featureName; }) != -1;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::getSlangSession(slang::ISession** outSlangSession)
{
*outSlangSession = slangContext.session.get();
slangContext.session->addRef();
return SLANG_OK;
}
ShaderComponentID ShaderCache::getComponentId(slang::TypeReflection* type)
{
ComponentKey key;
key.typeName = UnownedStringSlice(type->getName());
switch (type->getKind())
{
case slang::TypeReflection::Kind::Specialized:
// TODO: collect specialization arguments and append them to `key`.
SLANG_UNIMPLEMENTED_X("specialized type");
default:
break;
}
key.updateHash();
return getComponentId(key);
}
ShaderComponentID ShaderCache::getComponentId(UnownedStringSlice name)
{
ComponentKey key;
key.typeName = name;
key.updateHash();
return getComponentId(key);
}
ShaderComponentID ShaderCache::getComponentId(ComponentKey key)
{
ShaderComponentID componentId = 0;
if (componentIds.TryGetValue(key, componentId))
return componentId;
OwningComponentKey owningTypeKey;
owningTypeKey.hash = key.hash;
owningTypeKey.typeName = key.typeName;
owningTypeKey.specializationArgs.addRange(key.specializationArgs);
ShaderComponentID resultId = static_cast<ShaderComponentID>(componentIds.Count());
componentIds[owningTypeKey] = resultId;
return resultId;
}
void ShaderCache::init(ISlangFileSystem* cacheFileSystem)
{
fileSystem = cacheFileSystem;
ComPtr<ISlangBlob> indexFileBlob;
if (fileSystem && fileSystem->loadFile("index", indexFileBlob.writeRef()) == SLANG_OK)
{
UnownedStringSlice indexText = UnownedStringSlice(static_cast<const char*>(indexFileBlob->getBufferPointer()));
TokenReader reader = TokenReader(indexText);
auto componentCountInFileSystem = reader.ReadUInt();
for (uint32_t i = 0; i < componentCountInFileSystem; i++)
{
OwningComponentKey key;
auto componentId = reader.ReadUInt();
key.typeName = reader.ReadWord();
key.specializationArgs.setCount(reader.ReadUInt());
for (auto& arg : key.specializationArgs)
arg = reader.ReadUInt();
componentIds[key] = componentId;
}
}
}
void ShaderCache::writeToFileSystem(ISlangMutableFileSystem* outputFileSystem)
{
StringBuilder indexBuilder;
indexBuilder << componentIds.Count() << Slang::EndLine;
for (auto id : componentIds)
{
indexBuilder << id.Value << " ";
indexBuilder << id.Key.typeName << " " << id.Key.specializationArgs.getCount();
for (auto arg : id.Key.specializationArgs)
indexBuilder << " " << arg;
indexBuilder << Slang::EndLine;
}
outputFileSystem->saveFile("index", indexBuilder.getBuffer(), indexBuilder.getLength());
for (auto& binary : shaderBinaries)
{
ComPtr<ISlangBlob> blob;
binary.Value->writeToBlob(blob.writeRef());
outputFileSystem->saveFile(String(binary.Key).getBuffer(), blob->getBufferPointer(), blob->getBufferSize());
}
}
Slang::RefPtr<ShaderBinary> ShaderCache::tryLoadShaderBinary(ShaderComponentID componentId)
{
Slang::ComPtr<ISlangBlob> entryBlob;
Slang::RefPtr<ShaderBinary> binary;
if (shaderBinaries.TryGetValue(componentId, binary))
return binary;
if (fileSystem && fileSystem->loadFile(String(componentId).getBuffer(), entryBlob.writeRef()) == SLANG_OK)
{
binary = new ShaderBinary();
binary->loadFromBlob(entryBlob.get());
return binary;
}
return nullptr;
}
void ShaderCache::addShaderBinary(ShaderComponentID componentId, ShaderBinary* binary)
{
shaderBinaries[componentId] = binary;
}
void ShaderCache::addSpecializedPipeline(PipelineKey key, Slang::ComPtr<IPipelineState> specializedPipeline)
{
specializedPipelines[key] = specializedPipeline;
}
struct ShaderBinaryEntryHeader
{
StageType stage;
uint32_t nameLength;
uint32_t codeLength;
};
Result ShaderBinary::loadFromBlob(ISlangBlob* blob)
{
MemoryStreamBase memStream(Slang::FileAccess::Read, blob->getBufferPointer(), blob->getBufferSize());
uint32_t nameLength = 0;
ShaderBinaryEntryHeader header;
if (memStream.read(&header, sizeof(header)) != sizeof(header))
return SLANG_FAIL;
const uint8_t* name = memStream.getContents().getBuffer() + memStream.getPosition();
const uint8_t* code = name + header.nameLength;
entryPointName = reinterpret_cast<const char*>(name);
stage = header.stage;
source.addRange(code, header.codeLength);
return SLANG_OK;
}
Result ShaderBinary::writeToBlob(ISlangBlob** outBlob)
{
OwnedMemoryStream outStream(FileAccess::Write);
ShaderBinaryEntryHeader header;
header.stage = stage;
header.nameLength = static_cast<uint32_t>(entryPointName.getLength() + 1);
header.codeLength = static_cast<uint32_t>(source.getCount());
outStream.write(&header, sizeof(header));
outStream.write(entryPointName.getBuffer(), header.nameLength - 1);
uint8_t zeroTerminator = 0;
outStream.write(&zeroTerminator, 1);
outStream.write(source.getBuffer(), header.codeLength);
RefPtr<RawBlob> blob = new RawBlob(outStream.getContents().getBuffer(), outStream.getContents().getCount());
*outBlob = blob.detach();
return SLANG_OK;
}
IShaderObjectLayout* ShaderObjectLayoutBase::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IShaderObjectLayout)
return static_cast<IShaderObjectLayout*>(this);
return nullptr;
}
void ShaderObjectLayoutBase::initBase(RendererBase* renderer, slang::TypeLayoutReflection* elementTypeLayout)
{
m_renderer = renderer;
m_elementTypeLayout = elementTypeLayout;
m_componentID = m_renderer->shaderCache.getComponentId(m_elementTypeLayout->getType());
}
// Get the final type this shader object represents. If the shader object's type has existential fields,
// this function will return a specialized type using the bound sub-objects' type as specialization argument.
Result ShaderObjectBase::getSpecializedShaderObjectType(ExtendedShaderObjectType* outType)
{
if (shaderObjectType.slangType)
*outType = shaderObjectType;
ExtendedShaderObjectTypeList specializationArgs;
SLANG_RETURN_ON_FAIL(collectSpecializationArgs(specializationArgs));
if (specializationArgs.getCount() == 0)
{
shaderObjectType.componentID = getLayout()->getComponentID();
shaderObjectType.slangType = getLayout()->getElementTypeLayout()->getType();
}
else
{
shaderObjectType.slangType = getRenderer()->slangContext.session->specializeType(
getElementTypeLayout()->getType(),
specializationArgs.components.getArrayView().getBuffer(), specializationArgs.getCount());
shaderObjectType.componentID = getRenderer()->shaderCache.getComponentId(shaderObjectType.slangType);
}
*outType = shaderObjectType;
return SLANG_OK;
}
Result RendererBase::maybeSpecializePipeline(ShaderObjectBase* rootObject)
{
auto currentPipeline = getCurrentPipeline();
auto pipelineType = currentPipeline->desc.type;
if (currentPipeline->unspecializedPipelineState)
currentPipeline = currentPipeline->unspecializedPipelineState;
// If the currently bound pipeline is specializable, we need to specialize it based on bound shader objects.
if (currentPipeline->isSpecializable)
{
specializationArgs.clear();
SLANG_RETURN_ON_FAIL(rootObject->collectSpecializationArgs(specializationArgs));
// Construct a shader cache key that represents the specialized shader kernels.
PipelineKey pipelineKey;
pipelineKey.pipeline = currentPipeline;
pipelineKey.specializationArgs.addRange(specializationArgs.componentIDs);
pipelineKey.updateHash();
ComPtr<gfx::IPipelineState> specializedPipelineState = shaderCache.getSpecializedPipelineState(pipelineKey);
// Try to find specialized pipeline from shader cache.
if (!specializedPipelineState)
{
auto unspecializedProgram = static_cast<ShaderProgramBase*>(pipelineType == PipelineType::Compute
? currentPipeline->desc.compute.program
: currentPipeline->desc.graphics.program);
List<RefPtr<ShaderBinary>> entryPointBinaries;
auto unspecializedProgramLayout = unspecializedProgram->slangProgram->getLayout();
for (SlangUInt i = 0; i < unspecializedProgramLayout->getEntryPointCount(); i++)
{
auto unspecializedEntryPoint = unspecializedProgramLayout->getEntryPointByIndex(i);
UnownedStringSlice entryPointName = UnownedStringSlice(unspecializedEntryPoint->getName());
ComponentKey specializedKernelKey;
specializedKernelKey.typeName = entryPointName;
specializedKernelKey.specializationArgs.addRange(specializationArgs.componentIDs);
specializedKernelKey.updateHash();
// If the pipeline is not created, check if the kernel binaries has been compiled.
auto specializedKernelComponentID = shaderCache.getComponentId(specializedKernelKey);
RefPtr<ShaderBinary> binary = shaderCache.tryLoadShaderBinary(specializedKernelComponentID);
if (!binary)
{
// If the specialized shader binary does not exist in cache, use slang to generate it.
entryPointBinaries.clear();
ComPtr<slang::IComponentType> specializedComponentType;
ComPtr<slang::IBlob> diagnosticBlob;
auto result = unspecializedProgram->slangProgram->specialize(specializationArgs.components.getArrayView().getBuffer(),
specializationArgs.getCount(), specializedComponentType.writeRef(), diagnosticBlob.writeRef());
// TODO: print diagnostic message via debug output interface.
if (result != SLANG_OK)
return result;
// Cache specialized binaries.
auto programLayout = specializedComponentType->getLayout();
for (SlangUInt j = 0; j < programLayout->getEntryPointCount(); j++)
{
auto entryPointLayout = programLayout->getEntryPointByIndex(j);
ComPtr<slang::IBlob> entryPointCode;
SLANG_RETURN_ON_FAIL(specializedComponentType->getEntryPointCode(j, 0, entryPointCode.writeRef(), diagnosticBlob.writeRef()));
binary = new ShaderBinary();
binary->stage = gfx::translateStage(entryPointLayout->getStage());
binary->entryPointName = entryPointLayout->getName();
binary->source.addRange((uint8_t*)entryPointCode->getBufferPointer(), entryPointCode->getBufferSize());
entryPointBinaries.add(binary);
shaderCache.addShaderBinary(specializedKernelComponentID, binary);
}
// We have already obtained all kernel binaries from this program, so break out of the outer loop since we no longer
// need to examine the rest of the kernels.
break;
}
entryPointBinaries.add(binary);
}
// Now create specialized shader program using compiled binaries.
ComPtr<IShaderProgram> specializedProgram;
IShaderProgram::Desc specializedProgramDesc = {};
specializedProgramDesc.kernelCount = unspecializedProgramLayout->getEntryPointCount();
ShortList<IShaderProgram::KernelDesc> kernelDescs;
kernelDescs.setCount(entryPointBinaries.getCount());
for (Slang::Index i = 0; i < entryPointBinaries.getCount(); i++)
{
auto entryPoint = unspecializedProgramLayout->getEntryPointByIndex(i);;
auto& kernelDesc = kernelDescs[i];
kernelDesc.stage = entryPointBinaries[i]->stage;
kernelDesc.entryPointName = entryPointBinaries[i]->entryPointName.getBuffer();
kernelDesc.codeBegin = entryPointBinaries[i]->source.begin();
kernelDesc.codeEnd = entryPointBinaries[i]->source.end();
}
specializedProgramDesc.kernels = kernelDescs.getArrayView().getBuffer();
specializedProgramDesc.pipelineType = pipelineType;
SLANG_RETURN_ON_FAIL(createProgram(specializedProgramDesc, specializedProgram.writeRef()));
// Create specialized pipeline state.
switch (pipelineType)
{
case PipelineType::Compute:
{
auto pipelineDesc = currentPipeline->desc.compute;
pipelineDesc.program = specializedProgram;
SLANG_RETURN_ON_FAIL(createComputePipelineState(pipelineDesc, specializedPipelineState.writeRef()));
break;
}
case PipelineType::Graphics:
{
auto pipelineDesc = currentPipeline->desc.graphics;
pipelineDesc.program = specializedProgram;
SLANG_RETURN_ON_FAIL(createGraphicsPipelineState(pipelineDesc, specializedPipelineState.writeRef()));
break;
}
default:
break;
}
auto specializedPipelineStateBase = static_cast<PipelineStateBase*>(specializedPipelineState.get());
specializedPipelineStateBase->unspecializedPipelineState = currentPipeline;
shaderCache.addSpecializedPipeline(pipelineKey, specializedPipelineState);
}
setPipelineState(specializedPipelineState);
}
return SLANG_OK;
}
} // namespace gfx
<file_sep>/tools/gfx/render-graphics-common.h
#pragma once
#include "tools/gfx/renderer-shared.h"
#include "core/slang-basic.h"
#include "tools/gfx/slang-context.h"
namespace gfx
{
class GraphicsCommonProgramLayout;
class GraphicsCommonShaderProgram : public ShaderProgramBase
{
public:
GraphicsCommonProgramLayout* getLayout() const;
private:
friend class GraphicsAPIRenderer;
Slang::RefPtr<ShaderObjectLayoutBase> m_layout;
};
class GraphicsAPIRenderer : public RendererBase
{
public:
virtual SLANG_NO_THROW Result SLANG_MCALL createShaderObjectLayout(
slang::TypeLayoutReflection* typeLayout, IShaderObjectLayout** outLayout) SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL
createShaderObject(IShaderObjectLayout* layout, IShaderObject** outObject) SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL createRootShaderObject(
IShaderProgram* program,
IShaderObject** outObject) SLANG_OVERRIDE;
virtual SLANG_NO_THROW Result SLANG_MCALL
bindRootShaderObject(PipelineType pipelineType, IShaderObject* object) SLANG_OVERRIDE;
void preparePipelineDesc(GraphicsPipelineStateDesc& desc);
void preparePipelineDesc(ComputePipelineStateDesc& desc);
Result initProgramCommon(
GraphicsCommonShaderProgram* program,
IShaderProgram::Desc const& desc);
};
}
| fb4bfff1957df21a1c598e22851712702f391776 | [
"C++"
] | 10 | C++ | Checkmate50/slang | 39975b207e5db7de8feaaebfda2ae122c1850b26 | f753e53b25b833efea141ee59ebce11b17558f4e | |
refs/heads/main | <repo_name>nguyenminhtoan99/owlfashion<file_sep>/app/Http/Controllers/auth/AdminController.php
<?php
namespace App\Http\Controllers\auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\auth\LoginRequest;
use App\Model\Admin;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
class AdminController extends Controller
{
public function getLogin(){
return view('admin.auth.login');
}
public function postLogin(LoginRequest $request){
$admin = Admin::query()
->where('email', $request->get('email'))
->first();
if ($admin !== null) {
if (Hash::check($request->get('password'), $admin->password)) {
// $request->session()->put('login', $request->input('email'));
$request->session()->put('login', true);
return redirect('/admin/category/');
}
return back()->with('notification', 'Sai email hoặc mật khẩu')->withInput();
}
return back()->with('notification', 'Sai email hoặc mật khẩu')->withInput();
}
public function logout()
{
Auth::logout();
Session::forget('login');
//$request->session()->forget('login');
return redirect("login");
}
}
<file_sep>/app/Http/Controllers/admin/BrandController.php
<?php
namespace App\Http\Controllers\admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\BrandRequest;
use App\models\Brand;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Str;
class BrandController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$brand = Brand::all();
return view('admin.pages.brand.index')->with('brands', $brand);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.pages.brand.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(BrandRequest $request)
{
$data = $request->all();
$slug = Str::slug($request->name);
$data['slug'] = $slug;
$status = Brand::create($data);
if ($status) {
Toastr::success('Đã thêm thành công nha san xuat', 'Thông báo');
} else {
Toastr::error('Xảy ra lỗi, Vui lòng thử lại!', 'Thông báo');
}
return redirect()->route('brand.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$brand = Brand::findOrFail($id);
return view('admin.pages.brand.edit')->with('brand', $brand);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(BrandRequest $request, $id)
{
$brand = Brand::findOrFail($id);
$status = $brand->update($request->all());
if ($status) {
Toastr::success('Đã sửa thành công nha san xuat', 'Thông báo');
} else {
Toastr::error('Xảy ra lỗi, Vui lòng thử lại!', 'Thông báo');
}
return redirect()->route('category.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$brand = Brand::findOrFail($id);
$status = $brand->delete();
if ($status) {
Toastr::success('Đã xoá thành công nha san xuat', 'Thông báo');
} else {
Toastr::error('Xảy ra lỗi, Vui lòng thử lại!', 'Thông báo');
}
return redirect()->route('brand.index');
}
}
<file_sep>/routes/web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
return view('welcome');
});
Route::get('login', 'auth\AdminController@getLogin')->name('admin.login');
Route::post('login', 'auth\AdminController@postLogin')->name('admin.login');
Route::get('logout', 'auth\AdminController@logout')->name('admin.logout');;
Route::group(['prefix'=>'/admin','middleware' => ['login']], function () {
//DANH MUC
Route::get('category/create','admin\CategoryController@create')->name('category.create');
Route::post('category/create','admin\CategoryController@store')->name('category.store');
Route::get('category/','admin\CategoryController@index')->name('category.index');
Route::get('category/edit/{id}','admin\CategoryController@edit')->name('category.edit');
Route::put('category/update/{id}','admin\CategoryController@update')->name('category.update');
Route::get('category/delete/{id}','admin\CategoryController@destroy')->name('category.destroy');
//NHA SAN XUAT
Route::get('brand/create','admin\BrandController@create')->name('brand.create');
Route::post('brand/create','admin\BrandController@store')->name('brand.store');
Route::get('brand/','admin\BrandController@index')->name('brand.index');
Route::get('brand/edit/{id}','admin\BrandController@edit')->name('brand.edit');
Route::put('brand/update/{id}','admin\BrandController@update')->name('brand.update');
Route::get('brand/delete/{id}','admin\BrandController@destroy')->name('brand.destroy');
//SAN PHAM
Route::get('product/create','admin\ProductController@create')->name('product.create');
Route::post('product/create','admin\ProductController@store')->name('product.store');
Route::get('product/','admin\ProductController@index')->name('product.index');
Route::get('product/edit/{id}','admin\ProductController@edit')->name('product.edit');
Route::put('product/update/{id}','admin\ProductController@update')->name('product.update');
Route::get('product/delete/{id}','admin\ProductController@destroy')->name('product.destroy');
});
<file_sep>/app/models/Product.php
<?php
namespace App\models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
protected $fillable=['name','slug','description','cat_id','price','brand_id','discount','status','photo','size','quantity','condition'];
public function categories()
{
return $this->belongsto('App\models\Category','cat_id','id');
}
public function brands(){
return $this->belongsTo('App\models\Brand','brand_id','id');
}
public $timestamps = true;
}
<file_sep>/app/Http/Controllers/admin/ProductController.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\models\Brand;
use App\models\Category;
use App\models\Product;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Str;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products=Product::all();
return view('admin.pages.product.index')->with('products',$products);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$categories = Category::get();
$brands=Brand::get();
return view('admin.pages.product.create')
->with('categories', $categories)
->with('brands', $brands);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// $this->validate($request,[
// 'name'=>'string|required',
// 'description'=>'string|nullable',
// 'photo'=>'string|required',
// 'size'=>'nullable',
// 'quantity'=>"required|numeric",
// 'cat_id'=>'required|exists:categories,id',
// 'brand_id'=>'nullable|exists:brands,id',
// 'status'=>'required|in:active,inactive',
// 'condition'=>'required|in:default,new,hot',
// 'price'=>'required|numeric',
// 'discount'=>'nullable|numeric'
// ]);
$data=$request->all();
$slug=Str::slug($request->name);
$data['slug']=$slug;
$size=$request->input('size');
if($size){
$data['size']=implode(',',$size);
}
else{
$data['size']='';
}
if($request->hasFile('photo')){
$image=$request->file('photo');
if($image->isValid()){
$fileName=time() . "_" . rand(0,9999999) . "." .$image->getClientOriginalExtension();
$image->move(public_path('products'), $fileName);
$data['photo']=$fileName;
}
}
$status=Product::create($data);
if($status){
Toastr::success('Đã thêm thành công sản phẩm', 'Thông báo');
}
else{
Toastr::error('Xảy ra lỗi, Vui lòng thử lại!', 'Thông báo');
}
return redirect()->route('product.index');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product=Product::findOrFail($id);
return view('admin.pages.product.edit')->with('product',$product);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$product= Product::findOrFail($id);
$status = $product->update($request->all());
if($status){
Toastr::success('Đã sửa thành công sản phẩm', 'Thông báo');
}
else{
Toastr::error('Xảy ra lỗi, Vui lòng thử lại!', 'Thông báo');
}
return redirect()->route('product.index');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product=Product::findOrFail($id);
$status=$product->delete();
if($status){
Toastr::success('Đã xoá thành công sản phẩm', 'Thông báo');
}
else{
Toastr::error('Xảy ra lỗi, Vui lòng thử lại!', 'Thông báo');
}
return redirect()->route('product.index');
}
}
| d44fb2f6054096438bb8dfa60f61c693895e8ceb | [
"PHP"
] | 5 | PHP | nguyenminhtoan99/owlfashion | 9d430b10cdab3e9f4322f9e7cb177c38a8fd512e | 8959446f0e995501fcb1f2cab8a9d1c03a889322 | |
refs/heads/master | <repo_name>andrewn/radiotag-node-tester<file_sep>/main.js
module.exports = {
radiotag: require('./lib/radiotag'),
cpa: require('./lib/cpa')
};<file_sep>/bin/flow
#!/usr/bin/env node
var Promise = require('es6-promise').Promise,
radiotag = require('radiotag.js'),
cpa = require('cpa.js'),
config;
try {
config = require('../config.json').radiotag;
} catch (e) {
config = {};
}
var serverName = process.env['SERVER'],
server = config[serverName];
if (!server) {
console.error('No server', serverName, 'found in config.json');
process.exit();
}
var uri = server.uri,
stationId = server.stationId;
authProvider(stationId, uri)
.then(register, errorHandlerForStep('init'))
.then(requestUserCode, errorHandlerForStep('register'))
.then(askUserToVerifyCode, errorHandlerForStep('requestUserCode'))
.then(pollForAccessToken, errorHandlerForStep('askUserToVerifyCode'))
.then(tagWithAccessToken, errorHandlerForStep('pollForAccessToken'))
.then(displayTag, errorHandlerForStep('tagWithAccessToken'))
.then(null, errorHandlerForStep('catch all'));
/*
Return an error handler function with msg
*/
function errorHandlerForStep(msg) {
return function (error) {
console.error('Error: ', msg, error);
};
}
/*
Get auth provider
*/
function authProvider(stationId, uri) {
return new Promise(function (resolve, reject) {
console.log('Entire flow');
console.log('Station id:', stationId);
console.log('Base URI:', uri, '\n');
console.log('\nGet auth provider...');
radiotag.getAuthProvider(uri, function (error, authProviderBaseUrl, modes) {
if (error) {
reject(error);
} else {
console.log(' authProviderBaseUrl: ', authProviderBaseUrl);
console.log(' modes: ', modes);
resolve({
stationId: stationId,
uri: uri,
authProviderBaseUrl: authProviderBaseUrl,
modes: modes
});
}
});
});
}
/*
Register for a clientId and clientSecret
*/
function register(params) {
console.log('\nCPA register');
console.log(' authProviderBaseUrl', params.authProviderBaseUrl);
var domain = radiotag.utils.getDomain(params.uri);
params.domain = domain;
console.log(' domain', params.domain);
return new Promise(function (resolve, reject) {
cpa.device.registerClient(
params.authProviderBaseUrl,
'My Device Name',
'radiotag-node-test',
'0.0.1',
function (error, clientId, clientSecret) {
if (error) {
reject(error);
} else {
console.log('\nRegistered:');
console.log(' clientId %s, clientSecret %s', clientId, clientSecret);
params.clientId = clientId;
params.clientSecret = clientSecret;
resolve(params);
}
}
);
});
}
/*
CPA:
Get a user code to show to user
*/
function requestUserCode(params) {
return new Promise(function (resolve, reject) {
console.log('\nCPA request user code with ');
console.log(' authProvider', params.authProviderBaseUrl);
console.log(' clientId', params.clientId);
console.log(' clientSecret', params.clientSecret);
console.log(' domain', params.domain);
cpa.device.requestUserCode(
params.authProviderBaseUrl,
params.clientId,
params.clientSecret,
params.domain,
function (error, data) {
if (error) {
reject(error);
} else {
console.log('Got user code');
params.user = data;
resolve(params);
}
}
);
});
}
function askUserToVerifyCode(params) {
console.log('\n\n****\n');
console.log('Please visit ' + params.user.verification_uri + ' and enter code: ' + params.user.user_code);
console.log('\n****');
return Promise.resolve(params);
}
function pollForAccessToken(params) {
var pollIntervalInSecs = params.user.interval * 1000;
return new Promise(function (resolve, reject) {
/* Does a single request for access token
and resolve, rejects or schedules another request
*/
function accessToken() {
process.stdout.write('.');
cpa.device.requestUserAccessToken(
params.authProviderBaseUrl,
params.clientId,
params.clientSecret,
params.user.device_code,
params.domain,
function tokenDone(error, data) {
if (error) {
reject(error);
} else if (data) {
console.log(' access token data: ', data);
params.token = data;
resolve(params);
} else {
setTimeout(accessToken, pollIntervalInSecs);
}
}
);
}
accessToken();
});
}
function tagWithAccessToken(params) {
return new Promise(function (resolve, reject) {
radiotag.tag(
params.stationId,
params.uri,
params.token.access_token,
function (error, tag) {
if (error) {
reject(error);
} else {
resolve(tag);
}
}
);
});
}
function displayTag(tag) {
console.log('\n\n****');
console.log('Tagged! 🎉');
console.log(tag);
console.log('****');
return Promise.resolve(tag);
}
<file_sep>/README.md
A small utility for testing cpa.js and radiotag.js in node.js
Install
--
npm install
To use local radiotag.js:
npm link radiotag.js
To use local cpa.js:
npm link cpa.js
Configure and use
--
cp config.json.example config.json
### Entire flow:
To test the entire CPA -> radiotag flow then the minimum config you'll need is:
{
"radiotag" : {
"EBU": {
"stationId": "0.c222.ce15.ce1.dab",
"uri": "http://bbc1-cpa.ebu.io/"
}
}
}
Then run:
SERVER=EBU bin/flow
The entire CPA flow will run, prompting you with a URL and user code on the command line when necessary. When an access code is acuired then a tag will be made.
### Radiotag only
You can test any part of the radiotag.js API by adding a valid server URI, station ID and access token in the `radiotag` section of the config.
Then run:
SERVER=<name> bin/radiotag <action>
e.g.
SERVER=BBC bin/radiotag auth
stationId 0.c222.ce15.ce1.dab
accessToken ...
uri ...
null 'https://radiotag.api.bbci.co.uk/ap/' { client: false, user: true, anonymous: false }
### CPA only
You can test any part of the cpa.js API by adding valid keys in the `cpa` section of the config.
Then run:
SERVER=<name> bin/cpa <action>
e.g.
SERVER=BBC bin/cpa register
authProvider https://auth-cpa.ebu.io/
clientName My CPA device
clientId 100054
clientSecret f8960c7c324588145e5ba627d3abd1ed
domain bbc1-cpa.ebu.io
softwareId cpa-radiotag-node-test
softwareVersion 0.0.0
Register success: client_id: 1039455 client_secret: d6560b27efe15df67af0a14c2a90b9cc
<file_sep>/lib/radiotag.js
var radiotag = require('radiotag.js'),
config;
try {
config = require('../config.json').radiotag;
} catch (e) {
config = {};
}
var serverName = process.env['SERVER'],
server = config[serverName];
if (!server) {
console.error('No server', serverName, 'found in config.json');
process.exit();
}
var stationId = server.stationId,
accessToken = server.accessToken,
uri = server.uri;
console.log('stationId', stationId);
console.log('accessToken', accessToken);
console.log('uri', uri);
module.exports = {
tag: function () {
radiotag.tag(stationId, uri, accessToken, tagDone);
},
list: function () {
radiotag.listTags(uri, accessToken, listDone);
},
auth: function () {
radiotag.getAuthProvider(uri, authDone);
}
}
function listDone(error, tags) {
console.log('List', error, tags);
}
function tagDone(error, tag) {
if (error) {
console.error('Tag error', error);
} else {
console.log('Tag', tag);
}
}
function authDone(err, authProviderBaseUrl, modes) {
console.log(err, authProviderBaseUrl, modes);
} | 53f532605a10064eb4fdce16c08d14568957c0d9 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | andrewn/radiotag-node-tester | 736aa4cc8f7be7625213273af51a36fd7c5f84f3 | c9f2b94add65b23394e5230594d3acd546897453 | |
refs/heads/master | <repo_name>mohit-agarwal/cassis<file_sep>/parse_first_line.py
# Author: <NAME>
import urllib2
from pyparsing import *
# Group together the tokens belonging to a column header.
def group_tokens(tokens):
return reduce(lambda x, y : x + " " + y, tokens)
# Parse firse line of the dataset.
def parse(data):
real_number = Word(nums+'.')
natural_number = Word(nums)
alpha_word = Word(alphas)
alphanum_word = Word(alphas+nums+'-')
mid_header = (natural_number + OneOrMore(alpha_word)).setParseAction(lambda s,l,t : group_tokens(t))
last_header = (natural_number + OneOrMore(alphanum_word)).setParseAction(lambda s,l,t : group_tokens(t))
grammar = real_number + mid_header + mid_header + mid_header + mid_header + last_header
print grammar.parseString(data)
# Get first line of the dataset.
def getFirstLine():
target_url = 'http://kurucz.harvard.edu/atoms/1401/gf1401.gam'
fp = urllib2.urlopen(target_url)
return fp.readline()
def main():
first_line = getFirstLine()
parse(first_line)
if __name__ == '__main__':
main()
| 235a2f3e0bc216e586eda0cb68f4e5fb31673b43 | [
"Python"
] | 1 | Python | mohit-agarwal/cassis | 8a5aabedf3d0cc4198b4f2305eb67ebc902d4367 | b830152507d05800b3d756cd4e99d7d78d7012ff | |
refs/heads/master | <file_sep>package a8;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Color;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class LifeView extends JPanel implements ActionListener, ChangeListener, LifeSpotListener {
private ArrayList<LifeViewListener> _listeners;
private PaintPanel _board;
private JPanel _bottom_panel, _game_control, _rate_control;
private JLabel _dimensionlabel, _ratelabel;
private JTextField _dimensionbox, _ratebox;
private JSlider _sleeptime_slider;
private JButton _advance, _reset, _clear, _setdimension, _setrate, _toggletorus,_togglerunning;
public LifeView(int dimension) {
_board = new PaintPanel(dimension,this);
_board.addListener(this);
setLayout(new BorderLayout());
add(_board, "Center");
_bottom_panel = new JPanel();
_bottom_panel.setLayout(new GridLayout(2,1));
// game control panel
_game_control = new JPanel();
_togglerunning = new JButton("\u25B6");
_togglerunning.addActionListener(this);
_advance = new JButton("Adv.");
_advance.addActionListener(this);
_clear = new JButton("Clear");
_clear.addActionListener(this);
_reset = new JButton("Reset");
_reset.addActionListener(this);
_sleeptime_slider = new JSlider(10,1000);
_sleeptime_slider.setValue(50);
_sleeptime_slider.setSize(new Dimension(40,20));
_sleeptime_slider.addChangeListener(this);
_game_control.add(_sleeptime_slider);
_game_control.add(_togglerunning);
_game_control.add(_advance);
_game_control.add(_reset);
_game_control.add(_clear);
// rate control panel
_rate_control = new JPanel();
_setdimension = new JButton("Set Dim.");
_dimensionlabel = new JLabel();
_dimensionlabel.setText(Integer.toString(dimension));
_setdimension.addActionListener(this);
_dimensionbox = new JTextField(3);
_setrate = new JButton("Set Rates");
_setrate.addActionListener(this);
_ratebox = new JTextField(5);
_ratelabel = new JLabel("3,3,2,3");
_toggletorus = new JButton("Torus off");
_toggletorus.addActionListener(this);
_rate_control.add(_dimensionlabel);
_rate_control.add(_dimensionbox);
_rate_control.add(_setdimension);
// _rate_control.add(new JLabel("(lb,hb,ls,hs)"));
_rate_control.add(_ratelabel);
_rate_control.add(_ratebox);
_rate_control.add(_setrate);
_rate_control.add(_toggletorus);
_bottom_panel.add(_game_control);
_bottom_panel.add(_rate_control);
add(_board,BorderLayout.CENTER);
add(_bottom_panel, BorderLayout.SOUTH);
resetView();
_listeners = new ArrayList<LifeViewListener>();
}
public void updatePanel(boolean[][] board) {
_board.update(board);
}
public void resetView() {
remove(_board);
add(_board, "Center");
revalidate();
repaint();
}
public void color(int x, int y, boolean alive) {
if (alive) {
_board.setAlive(x, y);
} else {
_board.setDead(x, y);
}
}
public PaintPanel getBoard() {
return _board;
}
// button actionPerformed
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(_advance.getText())) {
for (LifeViewListener l : _listeners) {
l.advancePressed();
}
}
if (e.getActionCommand().equals(_clear.getText())) {
for (LifeViewListener l : _listeners) {
l.clear();
}
}
if (e.getActionCommand().equals(_reset.getText())) {
for (LifeViewListener l : _listeners) {
l.reset();
}
}
if (e.getActionCommand().equals(_togglerunning.getText())) {
for (LifeViewListener l : _listeners) {
l.toggleThread();
if (_togglerunning.getText().equals("\u25B6")) {
_togglerunning.setText("\u23F8");
} else {
_togglerunning.setText("\u25B6");
}
}
}
if (e.getActionCommand().equals(_toggletorus.getText())) {
for (LifeViewListener l : _listeners) {
l.toggleTorusMode();
if (_toggletorus.getText().equals("Torus off")) {
_toggletorus.setText("Torus on");
} else {
_toggletorus.setText("Torus off");
}
}
}
if (e.getActionCommand().equals(_setdimension.getText())) {
for (LifeViewListener l : _listeners) {
int dim = 0;
try {
dim = Integer.parseInt(_dimensionbox.getText());
} catch (NumberFormatException f) {
_dimensionlabel.setText("Invalid input");
}
if (dim < 10 || dim > 500) {
_dimensionlabel.setText("Illegal dimension");
return;
}
l.changeDimension(dim);
_dimensionlabel.setText(_dimensionbox.getText());
_dimensionbox.setText("");
}
}
if (e.getActionCommand().equals(_setrate.getText())) {
for (LifeViewListener l : _listeners) {
String rates = _ratebox.getText();
int lb = 0;
int hb = 0;
int ls = 0;
int hs = 0;
try {
lb = rates.charAt(0)-48;
hb = rates.charAt(2)-48;
ls = rates.charAt(4)-48;
hs = rates.charAt(6)-48;
} catch (StringIndexOutOfBoundsException f) {
_ratelabel.setText("invalid input");
return;
}
if ((lb+hb+ls+hs) > 32 || (lb+hb+ls+hs) < 0 || (!(lb <= hb)) || (!(ls <= hs))) {
_ratelabel.setText("invalid rates");
return;
}
l.changeRates(lb,hb,ls,hs);
_ratelabel.setText(lb+","+hb+","+ls+","+hs);
_ratebox.setText("");
}
}
}
public void spotClicked(int x, int y) {
for (LifeViewListener l : _listeners) {
l.spotChanged(x,y);
}
}
public void setDimension(int dimension) {
_board.setDimension(dimension);
resetView();
}
// convenience for adding and removing listeners
public void addListener(LifeViewListener listener) {
_listeners.add(listener);
}
public void removeListener(LifeViewListener listener) {
_listeners.remove(listener);
}
@Override
public void stateChanged(ChangeEvent e) {
JSlider src = (JSlider) e.getSource();
for (LifeViewListener l : _listeners) {
l.changeSleepTime(src.getValue());
}
}
}
<file_sep>package a8;
public interface LifeSpotListener {
public void spotClicked(int x, int y);
}<file_sep>package a8;
import java.awt.Color;
import struct.Spot;
public class LifeController implements LifeViewListener, LifeModelObserver {
private LifeView _view;
private LifeModel _model;
private ModelRunner _runner;
public LifeController(LifeView view, LifeModel model) {
_view = view;
_model = model;
_runner = new ModelRunner(_model);
_runner.start();
_view.addListener(this);
_model.addObserver(this);
_view.updatePanel(_model.getBoard());
}
@Override
public void updateSpot(int x, int y, boolean alive) {
_view.color(x, y, alive);
}
@Override
public void spotChanged(int x, int y) {
if (_model.isAlive(x, y)) {
_model.setDead(x, y);
} else {
_model.setAlive(x,y);
}
pushModel();
}
public void pushModel() {
_view.updatePanel(_model.getBoard());
}
@Override
public void clear() {
_model.clear();
}
@Override
public void reset() {
_model.reset();
}
@Override
public void advancePressed() {
_model.advance();
}
@Override
public void changeDimension(int dimension) {
_model.setDimension(dimension);
_view.setDimension(dimension);
pushModel();
}
@Override
public void changeRates(int lowbirth, int highbirth, int lowsurvival, int highsurvival) {
_model.setRates(lowbirth, highbirth, lowsurvival, highsurvival);
}
@Override
public void toggleTorusMode() {
_model.toggleTorusMode();
if (_model.getTorusMode()) {
}
}
@Override
public void toggleThread() {
System.out.println("toggle thread");
if (_runner.isPaused()) {
_runner.resum();
System.out.println("resume");
} else {
_runner.pause();
}
}
@Override
public void changeSleepTime(int sleeptime) {
_runner.setSleepTime(sleeptime);
}
}<file_sep>package a8;
public class ModelRunner extends Thread {
private LifeModel _model;
private volatile boolean _running;
private volatile boolean _paused;
private int _sleeptime;
private Object lock;
public ModelRunner(LifeModel model) {
_model = model;
_running = true;
_paused = true;
_sleeptime = 50;
lock = new Object();
}
@Override
public void run() {
while (_running) {
synchronized (lock) {
if (!_running) { // may have changed while waiting to
// synchronize on pauseLock
break;
}
if (_paused) {
try {
synchronized (lock) {
lock.wait(); // will cause this Thread to block until
// another thread calls pauseLock.notifyAll()
// Note that calling wait() will
// relinquish the synchronized lock that this
// thread holds on pauseLock so another thread
// can acquire the lock to call notifyAll()
// (link with explanation below this code)
}
} catch (InterruptedException ex) {
break;
}
if (!_running) { // running might have changed since we paused
break;
}
}
}
_model.advance();
try {
sleep(_sleeptime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void pause() {
_paused = true;
}
public void resum() {
synchronized (lock) {
_paused = false;
lock.notifyAll();
}
}
public boolean isPaused() {
return _paused;
}
public void setSleepTime(int time) {
if (time < 10) {throw new IllegalArgumentException("sleep length is too short");}
if (time > 1000) {throw new IllegalArgumentException("sleep length is too long");}
_sleeptime = time;
}
}
<file_sep>.PHONY: game run build clean
game: build
java -cp bin -Djava.awt.headless=true main.ExampleGame
run: build
java -cp bin main.Main
build: bin/
javac -d ./bin ./src/main/*
bin/:
mkdir -p ./bin
| 3f325e387dc61917cf17997e58e3b928458a8cab | [
"Java",
"Makefile"
] | 5 | Java | benjdod/a8 | 7c72f05354154229e08bd47207c2a8cc7c1258ff | eadda32c05a226dc3bb8d41f7d749e5574fe81ed | |
refs/heads/master | <repo_name>Tamanna8/Cannibals-and-Explorers<file_sep>/README.md
# Cannibals-and-Explorers-
This project solves the puzzle of cannibals and explorers using recursion
-----------------------------------------------------------------------------
Cannibals
<NAME>
Date: 10/27/2017
I tried to solve this puzzle or problem with the help of recursion. I used vectors because I have never used vectors before and I wanted to try to make the program with it. I thought to use looping method, but I figured that it won’t help me learn the new concept. So, I used vectors.
ALGORITHM PSEUDO CODE
If cannibals and explorer equals 3 and boat equals 1
then return 0
else if completed.at(10) is not equal 1 and boat equals 0
then completed.at(10) equal 1
temporary is equal to solution(initial Cannibals - 2, initial Explorer, final Explorer, final Cannibal + 2, 1)
output as --- EEECCC
else if completed.at(9) not equals 1
then completed.at(9) equal 1
temporary is equal to solution(initial Cannibals + 1, initial Explorer, final Explorer, final Cannibal - 1, 0)
output as CC EEEC
else if (completed.at(8) not equals 1 and b equals 0
then completed.at(8) equal 1
temporary is equal to solution(initial Cannibals - 2, initial Explorer, final Explorer, final Cannibal + 2, 1)
output as C EEECC
else if completed.at(7) not equal 1
then completed.at(7) equal 1;
temporary is equal to solution(initial Cannibals + 1, initial Explorer, final Explorer, final Cannibal - 1, 0)
output as CCC EEE
else if completed.at(6) not equals 1 and b equals 0
then
completed.at(6) equal 1
temporary is equal to solution(initial Cannibals, initial Explorer - 2, final Explorer + 2, final Cannibal, 1)
output as CC EEEC
else if completed.at(5) not equals 1
then completed.at(5) equal 1
temporary is equal to solution(initial Cannibals + 1, initial Explorer + 1, final Explorer - 1, final Cannibal - 1, 0)
output as CCEE EC
else if completed.at(4) not equals 1 and b equals 0
then completed.at(4) equal 1;
temporary is equal to solution(initial Cannibals, initial Explorer - 2, final Explorer + 2, final Cannibal, 1)
output as CE EECC
else if completed.at(3) not equals1
then completed.at(3) equal 1;
temporary is equal to solution(initial Cannibals + 1, initial Explorer, final Explorer, final Cannibal - 1, 0)
output as CEEE CC
else if completed.at(2) not equals 1 and b equals 0
then completed.at(2) equal 1
temporary is equal to solution(initial Cannibals - 2, initial Explorer, final Explorer, final Cannibal + 2, 1)
output as EEE CCC
else if completed.at(1) not equals 1
then completed.at (1) equal 1
temporary is equal to solution(initial Cannibals, initial Explorer + 1, final Explorer - 1, final Cannibal, 0)
output as CCEEE C
else if completed.at(0) not equals 1 and b equals 0
then completed.at(0) equal 1
temporary is equal to solution(initial Cannibals - 1, initial Explorer - 1, final Explorer + 1, final Cannibal + 1, 1)
output as CCEE EC
finally, return temporary
OUTPUT
The output shows the solution of cannibals and explorers problem’s solutions
So, the left side is the initial state of the cannibals and the exploders where both cannibals and explorers are 3 each, which is a valid state.
The steps are as follows:
• The boat goes on the right side with 1 Cannibal and 1 Explorer
• returns back to left with 1 Explorer
• 2 Cannibals goes to right side leaving 3 Explorers on left and 3 Cannibals on right side
• 1 Cannibal comes back to left side and 2 Explorers goes to the right side
• 1 Explorer and 1 Cannibal comes back to the left side leaving 1 Explorer and 1 Cannibal on the right
• 2 Explorers goes to the right side leaving 2 Cannibals on left
• 1 Cannibals goes back to left which makes 3 Cannibals on left and 3 Explorers on the right side
• 2 Cannibals goes to right and leaves 1 Cannibal on the right side
• 1 Cannibal goes back to get the last Cannibals
• Both Cannibals goes to the right side
• All 3 Cannibals and 3 Explorers are on the right side
<file_sep>/cannibals.cpp
/*
Name: <NAME>
Version: 10/27/2017 1.0
cannibals.cpp : Defines the entry point for the console application.Solves the puzzle using recursion
*/
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
iniCal= cannibals on left side of the bank
iniExpo= explorer on left side of the bank
finCal= cannibals on the right side of the bank
finExpo= explorer on the right side of the bank
b= boat
*/
int iniCal = 3, iniExpo = 3, finExpo = 0, finCal = 0, b = 0, temp = 1;
/* --------------------------------------------Headers------------------------------------------
headers for methods
*/
class cannibals
{
public:
cannibals();
int solution(int iniCal, int iniExpo, int finExpo, int finCal, int b);
void show();
vector<string> result;
vector<int> completed;
};
/* --------------------------------------------cannibals() ------------------------------------------
constructor for cannibals
*/
cannibals::cannibals()
{
completed.assign(11, 0);
result.push_back("LEFT RIGHT ");
result.push_back(" ");
result.push_back("EEECCC --- ");
}
/* --------------------------------------------solution------------------------------------------------
this method calculates the right soluton using recursion. this method is using various if and else
conditions to get the right solution.
*/
int cannibals::solution(int iniCal, int iniExpo, int finExpo, int finCal, int b)
{
if (finCal == 3 && finExpo == 3 && b == 1) {
return 0;
}
else if (completed.at(10) != 1 && (b == 0))
{
completed.at(10) = 1;
temp = solution(iniCal - 2, iniExpo, finExpo, finCal + 2, 1);
result.push_back("--- EEECCC");
}
else if (completed.at(9) != 1)
{
completed.at(9) = 1;
temp = solution(iniCal + 1, iniExpo, finExpo, finCal - 1, 0);
result.push_back("CC EEEC");
}
else if (completed.at(8) != 1 && (b == 0))
{
completed.at(8) = 1;
temp = solution(iniCal - 2, iniExpo, finExpo, finCal + 2, 1);
result.push_back("C EEECC");
}
else if (completed.at(7) != 1)
{
completed.at(7) = 1;
temp = solution(iniCal + 1, iniExpo, finExpo, finCal - 1, 0);
result.push_back("CCC EEE");
}
else if (completed.at(6) != 1 && (b == 0))
{
completed.at(6) = 1;
temp = solution(iniCal, iniExpo - 2, finExpo + 2, finCal, 1);
result.push_back("CC EEEC");
}
else if (completed.at(5) != 1)
{
completed.at(5) = 1;
temp = solution(iniCal + 1, iniExpo + 1, finExpo - 1, finCal - 1, 0);
result.push_back("CCEE EC");
}
else if (completed.at(4) != 1 && (b == 0))
{
completed.at(4) = 1;
temp = solution(iniCal, iniExpo - 2, finExpo + 2, finCal, 1);
result.push_back("CE EECC");
}
else if (completed.at(3) != 1)
{
completed.at(3) = 1;
temp = solution(iniCal + 1, iniExpo, finExpo, finCal - 1, 0);
result.push_back("CEEE CC");
}
else if (completed.at(2) != 1 && (b == 0))
{
completed.at(2) = 1;
temp = solution(iniCal - 2, iniExpo, finExpo, finCal + 2, 1);
result.push_back("EEE CCC");
}
else if (completed.at(1) != 1)
{
completed.at(1) = 1;
temp = solution(iniCal, iniExpo + 1, finExpo - 1, finCal, 0);
result.push_back("CCEEE C");
}
else if (completed.at(0) != 1 && (b == 0))
{
completed.at(0) = 1;
temp = solution(iniCal - 1, iniExpo - 1, finExpo + 1, finCal + 1, 1);
result.push_back("CCEE EC");
}
return temp;
}
/* --------------------------------------------show------------------------------------------
it is to show output of the right solution for cannibles and explorer puzzle after recursion
*/
void cannibals::show()
{
for (int i = 0; i < result.size(); i++) {
cout << result[i] << endl;
}
}
/* --------------------------------------------main------------------------------------------
it is the main method for output all the results
*/
int main()
{
cannibals c;
c.solution(iniCal, iniExpo, finExpo, finCal, b);
c.show();
return 0;
}
| 7951fb189eba889643a0cd19a6eaef9d0958a24d | [
"Markdown",
"C++"
] | 2 | Markdown | Tamanna8/Cannibals-and-Explorers | 341c0a2a4a196c830aaec17705b27b290916baa9 | 292593b7e0b7dd86441a24713299d815d49faef1 |